JQuery form submit adding request headers
Asked Answered
R

1

4

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 ?

Red answered 10/8, 2016 at 10:28 Comment(1)
No, it's not possible to add headers to a regular form submit using javascript.Sheritasherj
I
0

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();
});
Issykkul answered 21/11, 2019 at 0:38 Comment(6)
OP asked without AjaxCornew
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 possibleCornew
@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.