Spring ModelAndView not working with ajax call

2.6k Views Asked by At

Ajax calls a Spring Controller employee_edit but the ModelAndView is not working. It does not redirect to jsp page with object.I want to redirect to the page employee_registration.jsp with the object employee. Code has no error.

Ajax

 $('#example1 tbody').on( 'click', 'button1', function () {
                var eid = table.row( $(this).parents('tr') ).data().eid;
                $.ajax({
                    type:"GET",
                    url:"employee_edit?eid="+eid
                }); 

Controller

@RequestMapping(value="/employee_edit", method=RequestMethod.GET)
public ModelAndView RegitrationEdit(@RequestParam("eid") long eid)
{           
  Employee employee=employeeService.getEmployee(eid);
  ModelAndView mv=new ModelAndView(); 
  mv.setViewName("employee/employee_registration");
  mv.addObject("employee",employee);
  return mv;
}

After running the code it does not show any error. Going through the code ModelAndView("employee/employee_registration","employee",employee); but nothing happens. Thanks in advance.

2

There are 2 best solutions below

0
On BEST ANSWER

I think in your ajax call you need to add the success parameter. You can simply modify your call as

 $.ajax({
            type:"GET",
            url:"employee_edit",
            data:{"eid":eid},
            success:function(data){
            }
       });

or you can also add only the success parameter in your code

$.ajax({
            type:"GET",
            url:"employee_edit?eid="+eid
            success:function(data) { }
       });

But I prefer the first one. Its more clear.

This should complete the ajax call and your program should work.

0
On

When calling from ajax, ModelAndView will not work. You need to return the employee object as json by marking the the return type with annotation @ResponseBody

@RequestMapping(value="/employee_edit", method=RequestMethod.GET)
public @ResponseBody Employee RegitrationEdit(@RequestParam("eid") long eid)
{           
  Employee employee=employeeService.getEmployee(eid);    
  return employee;
}

After that upon successful call, you will get the response inside success callback.

$.ajax({
    type:"GET",
    url:"employee_edit?eid="+eid,
    success: function(data) {
        //here data is the employee object
        //process it here and redirect using window.location
    }
});