1

I use ajax to send text to my server. If I remove the line below it breaks.

xhr = new window.XMLHttpRequest();
xhr.open("POST", config.url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");  // removal causes error

I noticed that my get requests do not require a request header. In fact this is the only requestHeader I have ever used.

What exactly is x-www-form-urlencoded and why is it needed?

How / Does it relate to encodeURIComponent ,which I found that I must also run on text sent to the server?

  • https://developer.mozilla.org/en-US/docs/Setting_HTTP_request_headers and https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#setRequestHeader() – j08691 Mar 06 '13 at 21:46
  • GET requests pass all required data in the URL via query parameters. There's no "body", therefore no content. POSTs can send arbitrary data, and therefore require a content-type. – Marc B Mar 06 '13 at 21:52

2 Answers2

2

It does relate to encodeURIComponent(str), in that encodeURIComponent encodes a form component accordingly to the percentage encoding: http://en.wikipedia.org/wiki/Percent-encoding.

The WWW form URL encoding further specifies that fields that transmitted as NAME=CONTENT, where name and content are percentage encoded, and that the different fields are separated by an ampersand (&).

Kijewski
  • 25,517
  • 12
  • 101
  • 143
  • You can send raw text (or any binary data …), but the server side must understand it. Another common encoding is multipart/form-data, which is more verbose but better apt for unicode/binary data: http://stackoverflow.com/q/4007969/ – Kijewski Mar 06 '13 at 21:50
  • If your server side knows/assumes that there is JSON data in the content, you may as well omit the Content-Type header. But if you are a good person, you pass `application/json` as content type. ;) – Kijewski Mar 06 '13 at 21:57
  • Not. If you are writing both the client and server side script, it does not matter at all. You'd be free to invent your own content-types as well. – Kijewski Mar 06 '13 at 21:59
  • No that is actually `x-www-form-urlencoded`. If you would omit the `pipe=` and the `encodeURIComponent`, it'd be a proper JSON body. But on server side you would have to make changes accordingly. I use "plain" JSON bodies in a web project at my work (with werkzeug/Python on the server side), and it works fine in all browsers (at least since IE8). – Kijewski Mar 06 '13 at 22:06
1

This header defines correct encoding for POST variables.

See: http://en.wikipedia.org/wiki/POST_(HTTP)#Use_for_submitting_web_forms

tkeram
  • 214
  • 1
  • 5
  • I think that is kind of a lie as there is no default. If I omit it, it fails. Maybe just a different definition of "default"....`the default Internet media type is "application/x-www-form-urlencoded"` –  Mar 06 '13 at 22:00