I want to ask is it possible to specify headers before calling $(myForm).submit();
I know you can specify in AJAX post request but is it possible before this simple form submit ?
JQuery form submit adding request headers
No, it's not possible to add headers to a regular form submit using javascript. –
Sheritasherj
Yes you can. Requires some native JavaScript
drudgery, this is how I did it:
<!DOCTYPE html>
<html>
<body>
<h1>Custom Header Injection 1</h1>
<div id="header_demo">
<form id="custom_form">
<input type="hidden" name="name_1" value="${form.name_1}" />
<button type="button" onclick="submitFormAndHeader()">Submit Form</button>
</form>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<script>
function submitFormAndHeader() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("POST", "/v1/target-endpoint.do", true);
xhttp.setRequestHeader("custom_header", "test value of custom header");
xhttp.send($("#custom_form").serialize());
}
</script>
</body>
</html>
Added a function submitFormAndHeader
which creates an XMLHttpRequest object that adds the required headers and submits a HTML
DOM
form via HTTP POST
.
Alternatively, you can use Jquery submit handler and invoke the submitFormAndHeader()
function created above:
$( "#custom_form" ).on( "submit", function( event ) {
event.preventDefault();
submitFormAndHeader();
});
OP asked without Ajax –
Cornew
Hi @epascarello, yes XMLHttpRequest.send() is indeed an ajax call. However, original question was:
is it possible to specify headers before calling $(myForm).submit();
Here, we're adding a header during a form submit event and overriding it's default behaviour. –
Issykkul Yes it has nothing to do with Ajax.... Answer is.... not possible –
Cornew
@Cornew I have explained it is possible to add headers while calling
$(myForm).submit();
.. i.e. by passing a overriding $( "myForm" ).on( "submit", function( event ) {...
.. without using jquery's ajax function as was asked by @Donatas: $.ajax({ headers: { custom_header: 'test value of custom header' },...
–
Issykkul Ajax Headers is not going to do anything with a normal form submission. It will only make a difference if they make an Ajax Call. –
Cornew
yes,
$(myForm).submit();
is converted to an ajax request by customizing its default behaviour. Please try the code. –
Issykkul © 2022 - 2024 — McMap. All rights reserved.