How to make ajax call in spring framework

Write a server side method, with a mapping something as follows:

@RequestMapping("/getKids.html")   
public @ResponseBody
String getChildren(@RequestParam(value = "ocn") String ocn,
HttpServletRequest request, HttpServletResponse response)
{
return ocn.toUpperCase();
}

Here @ResponseBody tells the framework to return value of the method to the browser and not lookup for a view with that name.
You can optionally omit request and response parameters in the signature of the method, if you like to.

After removal of request and response the method will look like

@RequestMapping("/getKids.html")   
public @ResponseBody
String getChildren(@RequestParam(value = "ocn") String ocn)
{
return ocn.toUpperCase();
}

Write a javascript method as follows (This uses jquery to fire ajax request)

function populateSubAgents(obj)
{
$.ajax({
url: "getKids.html?ocn="+obj.value,
success: function(data) {
$("#subAgentName").html(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
if (XMLHttpRequest.status == 0) {
alert(' Check Your Network.');
} else if (XMLHttpRequest.status == 404) {
alert('Requested URL not found.');
} else if (XMLHttpRequest.status == 500) {
alert('Internel Server Error.');
} else {
alert('Unknown Error.\n' + XMLHttpRequest.responseText);
}
}
});
}

Advertisements

About Vineet Verma

Developer/Blogger/Gamer/Lazy Couch Potato...:P Need PDF Books: Knowledge Base
This entry was posted in AJAX, Spring. Bookmark the permalink.

1 Response to How to make ajax call in spring framework

  1. An alternate method of writing server side method is:
    1) Make the return type of the method to be void.
    2) What ever you want to return, write it in response.getWriter()

    @RequestMapping(“/getPrice.html”)
    public void getPrice(HttpServletRequest request,
    HttpServletResponse response, ModelMap model, String ocn)
    {
    try {
    response.setContentType(“text/html”);
    response.getWriter().write(“YOGESH”);
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s