Search code examples
javascripthtmlxmlhttprequest

How to submit a HTML form with header


I want to submit a form including a header during posting the request , is that possible ? I tried below code but I was unable to send the request with the defined header .


<html>
  <body>
  <script>
    var xhr = new XMLHttpRequest;
    xhr.setRequestHeader("Myheader" , "value")
  </script>
    <form action="https://example.com/myprofile/myedit" method="POST">
      <input type="hidden" name="firstname" value="Jacob&#32;" />
      <input type="hidden" name="email" value="jacob&#64;gmail&#46;com" />
      <input type="submit" value="Submit request" />
    </form>
  </body>
</html>


Solution

  • I want to submit a form including a header during posting the request , is that possible ?

    No.

    You can only add custom HTTP headers to a request if you are using XMLHttpRequest or fetch to make the request (so you can't if you are using a form submission to make the request).

    You could use the submit event to intercept the form submission and make the request with XMLHttpRequest or fetch instead … but then you'd need to handle the response with JS too.