JQuery: Send JSON Objects with an ajax request « Intelligrape Groovy & Grails Blogs

JQuery: Send JSON Objects with an ajax request

Posted by Amit Jain

Hi Friends,

Lets discuss today 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: <Url of the action>,
          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: <Url of the action>,
          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<JSON> 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

Hope this helpled!

~~Amit Jain~~
amit@intelligrape.com

http://www.IntelliGrape.com

  • Share/Bookmark
Tags: , ,
This entry was posted on June 11th, 2010 at 4:00 pm and is filed under Javascript/Ajax/JQuery . You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

6 Responses to “JQuery: Send JSON Objects with an ajax request”

  1. Tech says:

    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!

  2. CN says:

    Hi!

    I stumbled until I saw this:

    data: {students: JSON.stringify(jsonObjects) }

    Thanks a lot!

  3. Hi, you saved me just some time. Thanks alot!

  4. chuanhao.you says:

    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!

  5. Avery says:

    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’, …})

  6. This actually answered my problem, thanks!

Leave a Reply