How to submit a HTML form with header

10,192

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.

Share:
10,192

Related videos on Youtube

Joel Deleep
Author by

Joel Deleep

Updated on June 04, 2022

Comments

  • Joel Deleep
    Joel Deleep almost 2 years

    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>
    
    
  • Joel Deleep
    Joel Deleep almost 5 years
    so it is not possible to add a HTTP header like 'Content-Type' with XMLHttpRequest !! is there any other possibilities
  • Quentin
    Quentin almost 5 years
    @Coder13 — It's entirely possible to do that. I said that in the second paragraph of this answer! You just have to make the HTTP request using XMLHttpRequest. You can't use XMLHttpRequest to add a header to a form submission.
  • Joel Deleep
    Joel Deleep almost 5 years
    As far as i understood i have to make an http request and intercept and then add the header ? If yes can you please expand your answer with more explanation and code , thanks in advance
  • Quentin
    Quentin almost 5 years
  • Joel Deleep
    Joel Deleep almost 5 years
    can you please provide me a working code for the same , i am confused reading the docs and not a pro with js