[javascript] Send JSON data with jQuery

Why code below sent data as City=Moscow&Age=25 instead of JSON format?

var arr = {City:'Moscow', Age:25};
$.ajax(
   {
        url: "Ajax.ashx",
        type: "POST",
        data: arr,
        dataType: 'json',
        async: false,
        success: function(msg) {
            alert(msg);
        }
    }
);

This question is related to javascript jquery ajax

The answer is


Because you haven't specified neither request content type, nor correct JSON request. Here's the correct way to send a JSON request:

var arr = { City: 'Moscow', Age: 25 };
$.ajax({
    url: 'Ajax.ashx',
    type: 'POST',
    data: JSON.stringify(arr),
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    async: false,
    success: function(msg) {
        alert(msg);
    }
});

Things to notice:

  • Usage of the JSON.stringify method to convert a javascript object into a JSON string which is native and built-into modern browsers. If you want to support older browsers you might need to include json2.js
  • Specifying the request content type using the contentType property in order to indicate to the server the intent of sending a JSON request
  • The dataType: 'json' property is used for the response type you expect from the server. jQuery is intelligent enough to guess it from the server Content-Type response header. So if you have a web server which respects more or less the HTTP protocol and responds with Content-Type: application/json to your request jQuery will automatically parse the response into a javascript object into the success callback so that you don't need to specify the dataType property.

Things to be careful about:

  • What you call arr is not an array. It is a javascript object with properties (City and Age). Arrays are denoted with [] in javascript. For example [{ City: 'Moscow', Age: 25 }, { City: 'Paris', Age: 30 }] is an array of 2 objects.

You need to set the correct content type and stringify your object.

var arr = {City:'Moscow', Age:25};
$.ajax({
    url: "Ajax.ashx",
    type: "POST",
    data: JSON.stringify(arr),
    dataType: 'json',
    async: false,
    contentType: 'application/json; charset=utf-8',
    success: function(msg) {
        alert(msg);
    }
});

Because by default jQuery serializes objects passed as the data parameter to $.ajax. It uses $.param to convert the data to a query string.

From the jQuery docs for $.ajax:

[the data argument] is converted to a query string, if not already a string

If you want to send JSON, you'll have to encode it yourself:

data: JSON.stringify(arr);

Note that JSON.stringify is only present in modern browsers. For legacy support, look into json2.js


I wrote a short convenience function for posting JSON.

$.postJSON = function(url, data, success, args) {
  args = $.extend({
    url: url,
    type: 'POST',
    data: JSON.stringify(data),
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    async: true,
    success: success
  }, args);
  return $.ajax(args);
};

$.postJSON('test/url', data, function(result) {
  console.log('result', result);
});

It gets serialized so that the URI can read the name value pairs in the POST request by default. You could try setting processData:false to your list of params. Not sure if that would help.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios