How to make ajax call in spring framework

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

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

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)
url: "getKids.html?ocn="+obj.value,
success: function(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);

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()

    public void getPrice(HttpServletRequest request,
    HttpServletResponse response, ModelMap model, String ocn)
    try {
    } catch (IOException e) {
    // TODO Auto-generated catch block


Leave a Reply

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

You are commenting using your 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