- Should I ever manually specify the
setRequestHeader
as 'application/x-www-form-urlencoded' for an ajax POST request? - Is it necessary to manually define the
setRequestHeader
as 'multipart/form-data' when uploading files via ajax? - Do XMLHttpRequest and XMLHttpRequest2 have varying requirements for using the
setRequestHeader
method?
My intuition as a programmer tells me that the browser can determine which headers to send based on the values provided in the .open() and .send() methods. It seems like setRequestHeader
should only be used when custom headers need to be included. But is this assumption accurate in this context?
I am seeking an explanation of what really happens behind the scenes!
.
xhttp.setRequestHeader('Content-type', 'multipart/form-data'); // for file uploads
xhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded'); // for sending escaped 'form' data via POST
edit:
A similar question could be raised regarding the Connection or Content-length headers, which many tutorials recommend including. However, in practice, browsers tend to handle these headers internally rather than following the manual specifications.
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
edit2:
As seen in this Stack Overflow question, removing unnecessary headers like content-type resolved issues with file uploads. This raises the question of when exactly should setRequestHeader
be utilized!