Key points for sending JSON data with AJAX

ajaxMessage

ajax, contentType and data

  • be noted that the ajax call defaults to application/x-www-form-urlencoded
  • always convert and put a string in the data field to prevent auto data conversion to the default format
  • explicitly specify the contentType field: application/json; charset=utf-8

The right way

[sourcecode language=”javascript” wraplines=”false” collapse=”false”]
var myData = { firstName: "Bruce" };
$.ajax({
type: "POST",
url: "/webService/service1",
contentType: "application/json; charset=utf-8", //Content-Type
data: JSON.stringify(myData), //Request Body
dataType: "json", //Accept: application/json, text/javascript, */*; q=0.01
success: function (data) {}
});
[/sourcecode]

WRONG! contentType not match to data

[sourcecode language=”javascript” wraplines=”false” collapse=”false”]
var myData = { firstName: "Bruce" };
$.ajax({
type: "POST",
url: "/webService/service1",
contentType: "application/json; charset=utf-8", //Content-Type
data: myData, //not a string, converted to application/x-www-form-urlencoded
dataType: "json", //Accept: application/json, text/javascript, */*; q=0.01
success: function (data) {}
});
[/sourcecode]

Typical ajax call: application/x-www-form-urlencoded

[sourcecode language=”javascript” wraplines=”false” collapse=”false”]
var myData = { firstName: "Bruce" };
$.ajax({
type: "POST",
url: "/webService/service1",
data: myData, //not a string, converted to application/x-www-form-urlencoded
dataType: "json", //Accept: application/json, text/javascript, */*; q=0.01
success: function (data) {}
});
[/sourcecode]

  • contentType: When sending data to the server, use this content type. contentType must match to the actual type of data. Default is “application/x-www-form-urlencoded; charset=UTF-8”, which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it’ll always be sent to the server (even if no data is sent). If no charset is specified, data will be transmitted to the server using the server’s default charset; you must decode this appropriately on the server side.
  • data: data to be sent to the server. It is converted to a query string, if not already a string. It’s appended to the url for GET-requests. See processData option to prevent this automatic processing.
  • processData: by default, data passed in to the data option as an object will be processed and transformed into a query string, fitting to the default content-type “application/x-www-form-urlencoded”. If you want to send a DOM Document, or other non-processed data, set this option to false.
  • dataType: the type of data that you’re expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response.
POST http://localhost:18232/api/web HTTP/1.1
User-Agent: Fiddler
Host: localhost:18232
Content-Type: application/json
Accept: application/xml
Content-Length: 91
[{“id”:1,”FirstName”:”Bruce”,”LastName”:”Wu”},{“id”:2,”FirstName”:”Jack”,”LastName”:”Lee”}]

  • encodeURIComponent

encodeURIComponent escapes all characters except the following: alphabetic, decimal digits, - _ . ! ~ * ' ( )

To avoid unexpected requests to the server, you should call encodeURIComponent on any user-entered parameters that will be passed as part of a URI. For example, a user could type “Thyme &time=again” for a variable comment. Not using encodeURIComponent on this variable will give comment=Thyme%20&time=again. Note that the ampersand and the equal sign mark a new key and value pair. So instead of having a POST comment key equal to “Thyme &time=again“, you have two POST keys, one equal to “Thyme ” and another (time) equal to again.

For application/x-www-form-urlencoded (POST), per http://www.w3.org/TR/html401/interac…m-content-type, spaces are to be replaced by ‘+’, so one may wish to follow a encodeURIComponent replacement with an additional replacement of “%20” with “+”.

Leave a Reply