0
  1. Should I ever manually set setRequestHeader to 'application/x-www-form-urlencoded' for ajax POST?
  2. Should I ever manually set setRequestHeader to 'multipart/form-data' for ajax file upload?
  3. Are there different requirements for XMLHttpRequest and XMLHttpRequest2 regarding setRequestHeader?

Common programming sense is telling me that browser can easily decide what headers should be sent depending on values from .open() and .send() methods. And that setRequestHeader should be used only if I have some custom headers to send. But is this really the case here?

I am looking for "what's really going on under the hood" type of answer!

.

xhttp.setRequestHeader('Content-type', 'multipart/form-data');  // for files

xhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded'); // for POST escaped 'form' data

edit:

I could similarly ask for Connection or Content-length headers. Many tutorials recommend sending those headers. But in practice this is wrong. Browsers are considering those headers as unsafe and send internally calculated values.

http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");

edit2:

Like in this SO question everything started to work when I removed content-type and other nonsensical headers.
Now I really want to know what is under the hood of setRequestHeader and when should I really use it!

Community
  • 1
  • 1
CoR
  • 3,826
  • 5
  • 35
  • 42

1 Answers1

3

Should I ever manually set setRequestHeader to 'application/x-www-form-urlencoded' for ajax POST?

Yes. If you pass send() a string (which you would be for application/x-www-form-urlencoded) then the default content-type is text/plain.

Should I ever manually set setRequestHeader to 'multipart/form-data' for ajax file upload?

No. If you are using multipart/form-data for a file upload then you will be using a FormData object and XHR will set it for you.

If you set it to just multipart/form-data then you'll omit the boundary information and it won't work.

Are there different requirements for XMLHttpRequest and XMLHttpRequest2

Work on XHR 2 has been discontinued.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Surprisingly good answer :) Could you explain in little more detail `Work on XHR 2 has been discontinued`. – CoR Jul 02 '15 at 11:20
  • 1
    http://www.w3.org/TR/XMLHttpRequest2/ says "Work on this document has been discontinued and it should not be referenced or used as a basis for implementation." – Quentin Jul 02 '15 at 11:20