Does ajax post data need to be URI encoded?

It all depends on the content type.

Normally when a <form> uses the HTTP method POST then the form values are URL Encoded and placed in the body of the request. The content type header looks like this:

content-type: application/x-www-form-urlencoded

Most AJAX libraries will do this by default since it is universally accepted among web servers. However, there is nothing preventing you from simply serializing the data as JSON or XML and then sending it with a different content type.

content-type: application/json

or

content-type: text/xml

It's worth noting that the payload has nothing to do with AJAX! Under the hood they are all using the XmlHttpRequest object to send an HTTP request asynchronously to the server. It doesn't matter if you send Plain Text, JSON, XML, or even raw binary data so long as you tell the server how to interpret those bits.

The url encoding is purely a historical artifact of how <form> elements posted their data to the server before AJAX was around.


encodeURIComponent is to pass variables over links using GET

JSON.stringify() encodes automatically into utf8

only in some rare cases for example when you want to convert strange charachters to base64 the encodeURIComponent is used outside from GET.

here is an example

base64_encode=function(a){
 return window.btoa(unescape(encodeURIComponent(a)));
};

https://developer.mozilla.org/en-US/docs/Web/API/window.btoa

said that ..

if you use a REST API service every ajax GET request which is a string parameter needs to be encoded with encodeURIComponent.

here is an example using yql

https://stackoverflow.com/a/18302867/2450730


Josh's answer is good, but I think it's missing something. Traditionally form data was posted using the same format as querystrings. eg: param1=value1&param2=value2 and the only difference between a GET and POST is that POST puts these parameters in the message body whereas a GET puts them in the URL. However, the obvious problem is that if your parameter names or values include unescaped characters like & and =, then you'll screw up the server's ability to automatically parse the parameter collection, resulting in corruption of the data. Using Javascript's encodeURIComponent() function on each parameter value will escape all these characters for you.

So bottom line: if you are not using the old standard parameter collection on the server side--for example, if you are parsing JSON instead--then there's no need to URL encode the text. Also, there's no reason to URL encode if you aren't parsing out multiple parameters on the server side so running encodeURIComponent once on the entire message body makes no sense.

Side note: if you are using asp.net and trying to let users pass html to the server, encodeURIComponent will let you do this without disabling the request validation that normally prohibits this. I don't think sending it as JSON, alone, would accomplish this.

Tags:

Javascript

Php