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 ?

Donatas
  • 71
  • 1
  • 9

1 Answers1

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();
});
Himadri Pant
  • 2,171
  • 21
  • 22
  • OP asked without Ajax – epascarello Nov 21 '19 at 00:49
  • 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. – Himadri Pant Nov 21 '19 at 01:06
  • Yes it has nothing to do with Ajax.... Answer is.... not possible – epascarello Nov 21 '19 at 01:08
  • @epascarello 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' },...` – Himadri Pant Nov 21 '19 at 01:37
  • 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. – epascarello Nov 21 '19 at 02:00
  • yes, `$(myForm).submit();` is converted to an ajax request by customizing its default behaviour. Please try the code. – Himadri Pant Nov 21 '19 at 04:08