Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Send JSON Objects with an ajax request

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 288
    Comment on it

    Hi,
    To send an ajax request, we have number of functions in jQuery. But to send JSON object along with the request, I chose jQuer.ajax(). It takes various parameters url, type, data, dataType, beforeSend etc.
    See below steps

    jQuery.ajax({
              url: ,
              type: "POST",
              data: {name: "raj", id:4 },
              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 I can send JSON objects list as given below:

    var jsonObjects = [{id:4, name:"raj"}, {id:5, name:"inder"},{id:6, name:"om"},{id:4, name:"shiva"}];
    
    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 code here
              }
    });
    

    Here Json objects has not been written directly as data: jsonObjects. because it expects that the JSON object passed to it, written as key value pair. Therefore we made students the key.

    Now I need to expand the json objects -

    //this code 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
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: