JQuery: Send JSON Objects with an Ajax Request

11 / Jun / 2010 by Amit Jain 26 comments

Through my blog, I will discuss about sending JSON objects with ajax request using JQuery. We have number of functions in jQuery to kick-off an ajax request. But for sending JSON objects along with the request, I chose jQuer.ajax(). It takes various parameters url, type, data, dataType, beforeSend etc. Its API can be found here.

Lets look at example given below:

jQuery.ajax({
          url: ,
          type: "POST",
          data: {name: "amit", id:1 },
          dataType: "json",
          beforeSend: function(x) {
            if (x && x.overrideMimeType) {
              x.overrideMimeType("application/j-son;charset=UTF-8");
            }
          },
          success: function(result) {
 	     //Write your code here
          }
});      

The above example works for simple JSON object. Now lets see how we can send JSON objects list as given below:

var jsonObjects = [{id:1, name:"amit"}, {id:2, name:"ankit"},{id:3, name:"atin"},{id:1, name:"puneet"}];

jQuery.ajax({
          url: ,
          type: "POST",
          data: {students: JSON.stringify(jsonObjects) },
          dataType: "json",
          beforeSend: function(x) {
            if (x && x.overrideMimeType) {
              x.overrideMimeType("application/j-son;charset=UTF-8");
            }
          },
          success: function(result) {
 	     //Write your code here
          }
});

If you notice, for sending my json objects it has not been written directly as data: jsonObjects. As it expects the JSON object passed to it written as key value pair. So we made students the key. And since we have json objects stored in a variable, we need to expand the json objects list using stringify(), otherwise it would be sent as a java script object.

Now on the server we can parse the JSON object, and use it as the list of objects of type map. For example

//this code is written in grails 
import grails.converters.JSON;
List students = JSON.parse(params.students) //students in request params is parsed to json objects and stored in the List
println "Student id: " + students[0].studentId    //first element of the students list is accessed as a map holding a key studentId

Stay tuned for more updates and visit our product engineering innovations.

FOUND THIS USEFUL? SHARE IT

Tag -

Ajax jquery JSON

comments (26)

  1. Ankesh

    It’s ok. but If I will have to receive this object from server then which kind of parameter should I assign to JesonResult??

    Reply
  2. S Vishnu Vardhan

    Thanks for the post. I have been searching for this current solution for almost 3 and half hours. Now i got it. Thanks a lot

    Reply
  3. Ajay Sharma

    Thanks a lot Amit. You saved the day. I was having serious trouble receiving the data as I was not using JSON.strigify(). Your solution worked like charm.

    Reply
  4. Jquery ajax tutorial

    Incredible! Many thanks! I desired to produce in my small
    website or something that is. Can one include a
    fragment of your respective article in order to my site?

    Reply
  5. Anil

    I have a json of the following format which I need to send in the Ajax request through POST method:
    {
    “gbus”: [
    {
    “code”: “*”
    }
    ],
    “regions”: [
    {
    “code”: “*”
    }
    ],
    “offices”: [
    {
    “code”: “*”
    }
    ],
    “contracttypes”: [
    {
    “code”: “*”
    }
    ],
    “jobnumbers”: [
    {
    “code”: “*”
    }
    ],
    “disciplines”: [
    {
    “code”: “*”
    }
    ]
    }

    Its not working for me, giving 500 error always when I try to submit it.
    Please suggest if you have any idea.

    Reply
  6. HT

    Another way of sending complex(more than key value pair) json objects is via request body.To achieve this just set data to Json.stringify(jsonObjects)and set the processData flag to false to prevent automatic processing and transformation of the data into a query string. Also set contentType to “application/json” to make sure the server knows whats in the request body and handles is accordingly.

    var jsonObjects = [{id:1, name:”amit”}, {id:2, name:”ankit”},{id:3, name:”atin”},{id:1, name:”puneet”}];

    jQuery.ajax({
    url: ,
    type: “POST”,
    data: JSON.stringify(jsonObjects),
    processData:false,
    contentType : “application/json”,
    dataType:”json”
    beforeSend: function(x) {
    if (x && x.overrideMimeType) {
    x.overrideMimeType(“application/j-son;charset=UTF-8”);
    }
    },
    success: function(result) {
    //Write your code here
    }
    });

    And on the server side just get the data as request.getReader() or request.getInputStream() and parse it with the api of your choice.

    Reply
  7. jacob

    this is what i need, but i want to know one more thing, like i want to send this json data to the php page,, then how do i receive the json data that is send through the ajax request??

    for example if we send the data normally means without any json format the we will $_GET[] to get the data..

    thanks

    Reply
  8. An Pham

    Hi,
    Thanks for your Example ^^
    This is just great and work well on IE, but it do not work on Chrome and Firfox!
    I think this is a problem about cross domain!

    Could you tell me the way to sole this problem!
    Expect your response soon!

    Thanks so much!

    Reply
  9. Avery

    A simpler way to specify the request’s mimetype is to use $.ajax’s “mimeType” attribute. “contentType” is similar but subtly different (specify both for good measure). So instead of calling $.ajax with a function literal for beforeSend, all you have to do is $.ajax({mimeType: ‘application/json’, contentType: ‘application/json’, …})

    Reply
  10. chuanhao.you

    very thank you!
    I’ve been failed to debug for more than 2 hours until I see this!

    It really helps!

    I thought jQuery.ajax can realize I was sending a JSON object and it would do something on that. But I’m wrong!

    Actually, I need to JSON.stringify it by myself!

    Reply
  11. Tech

    Hi dude. Nice post – one quick correction though. This line here:

    x.overrideMimeType(“application/j-son;charset=UTF-8”);

    That’s not the correct MIME type – try this:

    x.overrideMimeType(“application/json;charset=UTF-8”);

    Only a minor thing, but I thought I’d mention it in case it caused problems in the future.

    Cheers!

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *