Saturday, 6 July 2013

Ajax in Spring mvc Example Spring 3 MVC JSON Example

Ajax in Spring

Make a JSON Call On Any event of the html element to fetch the data from database

Ex:

<input type="button" Value="Call addMyData" onclick="addMyData()"  />

here we are defining a function  addMyData() which we have called on button click event.
 

function addMyData()
{
var name="Hello";
var address="Ahmedabad";
$.ajax({
type : "POST",
dataType : "json",
url :"/hello/addData",    //   This is RequestMapping Value of controller
                          //   if you are working in spring you can also write 
                          //   URL  like url: realativePath/adaData  or
                          //   url: realativePath/addData.do  etc
data : {
        name:name,
        address:address
        },
success : function(response) {
console.log(response);    //  This is response from the server After the                                       success of ajax call
},
error:function(s,st){                      // This will be executed if ajax call is failed  or return with error  ////
alert("error"+s);
}
}).done(function() {
alert("Call is Completed");           // This will execute when ajax call complete
});
}

IN CONTROLLER

you just need to return json data if u want to return any data 


just create a json object


JSONObject json=new JSONObject()


append some data to it

json.put("addedName",name)  // where name is your        variable in controller 
and send this in to response


response.getWriter().write(json.toString());
Now if u want to get this data in json call success


success:function(response){
alert(response.addedName);
}



IF any query ask me, i will back to you as fast as posible thanks for visiting this blog