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


<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";
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/  etc
data : {
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  ////
}).done(function() {
alert("Call is Completed");           // This will execute when ajax call complete


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

Now if u want to get this data in json call success


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