New to XMLHttpRequest, and here is some confusion for me:
-
Why must we set the content type when using the post method in a xmlhttprequest?
XHR.setRequestHeader(“Content-type”, “application/x-www-form-urlencoded”);
-
Isnt the default value application/x-www-form-urlencoded already?
HTTP/POST does not ask for that specific content-type when you do a HTTP/POST over AJAX (or for that matter via other means). It is up to you (and up to the server side program handling it). Read the second section for Why we must set it explicitly.
Very often, we serialise the form (percentile-encode it — a=b&c=d format) and send it across to the server. This format is
application/x-www-form-urlencoded. If you are sending an XML, you would useapplication/xml, for JSON you would useapplication/jsonand so on.As for GET request, there’s no body and hence we dont really need the content-type header.
I tried skimming through here for the default content-type header. I couldn’t find anything. However, when I tried doing a HTTP/POST AJAX request via chrome’s console, I noticed that chrome’s default is
application/xml.Just a piece of advice — never rely on default behaviour except when its explicitly stated and/or is a part of the standard. Why not set the content type explicitly?