Home Spring ModelAndView not working with ajax call
Reply: 2

Spring ModelAndView not working with ajax call

Brahma Dutt Sudhakaran
1#
Brahma Dutt Sudhakaran Published in 2017-12-07 19:12:33Z

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.

mhshimul
2#
mhshimul Reply to 2017-12-08 06:57:48Z

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
    }
}); 
rishon
3#
rishon Reply to 2017-12-08 07:19:05Z

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.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.305896 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO