-1

I am new to "jQuery ajax",I am sending the request to the server using ajax. I am sending the data ie no, name, class, age as normal parameters. My Requirement is , I want to send the data in JSON format. My code is,

function fun1() {

    $.ajaxSetup({
        jsonp: null,
        jsonpCallback: null
    });

    $.ajax({
        type: 'POST',
        url: 'register.action',
        dataType: 'json',
        data: {
            no: document.getElementById("id1").value,
            name: document.getElementById("id2").value,
            clas: document.getElementById("id3").value,
            age: document.getElementById("id4").value    
        },    
        success: function (data) {    
            printStudentDetails(data);    
        },
        error: function () {
            alert("failure");
        }
    });

}

My server side resource is java.

reddy
  • 667
  • 2
  • 9
  • 19

1 Answers1

0

try this:

$.ajaxSetup({
    jsonp: null,
    jsonpCallback: null
});

function fun1(){

    $.ajax({
        type: 'POST',
        url: 'register.action',
        dataType: 'json',
        data: {
            jsonData: JSON.stringify({
                no: $('#id1').val(),
                name: $('#id2').val(),
                clas: $('#id3').val(),
                age: $('#id4').val()
            }) 
        },    
        success: function (data) {    
            printStudentDetails(data);    
        },
        error: function () {
            alert("failure");
        }
    });

}

this will make a HTTP post to your server url and one of the post field will be called "jsonData" which will contain json encoded string value of your form data (which you can decode into array/object for manipulation/storage in your server).

Latheesan
  • 23,247
  • 32
  • 107
  • 201
  • how can i decode this json encoded string value at the server side.I am using java struts2 at the server side. – reddy Oct 24 '13 at 05:22
  • I don't use java, i answered the jquery/ajax potion of your question. Did a search on google and found [this](http://stackoverflow.com/a/11430777/2332336). You need to define in your java a class defintion of what your JSON data contains and decode back to data using this (EXAMPLE): `List userList = (List)JSON.deserialize(stringObject,List.class);` where "User" is the class defining the json data structure. – Latheesan Oct 24 '13 at 08:44