Wednesday, February 19, 2014

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);
      }     
    }
  });   
}

1 comment:

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

    ReplyDelete