I have an ajax on a jsp page which calls a spring controller through URL /check .  
$.ajax({
    type : "GET",
    url : "${pageContext.request.contextPath}/check",
    data : {
    "id" : ${articleCount}
    },
    success: function(data){
    //response from controller
    }
});
Now, the controller looks like,
@RequestMapping("/check")
public String check(@RequestParam Integer id, HttpServletRequest request,
        HttpServletResponse response, Model model) {
    boolean a = getSomeResult();
    if (a == true) {
        model.addAttribute("alreadySaved", true);
        return view;
    } else
        model.addAttribute("alreadySaved", false);
    return view;
}
I sent data using model and tried to access it in success: function(data) as "${alreadySaved}"but it shows blank. 
Is there any way I can receive that true/false data on the view page?
You have to add the @ResponseBody annotation for spring ajax calls example
@RequestMapping("/check")     
@ResponseBody
public String check(@RequestParam Integer id, HttpServletRequest request, HttpServletResponse response, Model model) {
    boolean a = getSomeResult();
    if (a == true) {
        model.addAttribute("alreadySaved", true);
        return view;
    } else {
        model.addAttribute("alreadySaved", false);
        return view;
    }
}
                        use @ResponseBody
Spring will bind the return value to outgoing HTTP response body when you add @ResponseBody annotation. 
@ResponseBody
public String check(@RequestParam Integer id, HttpServletRequest request, HttpServletResponse response, Model model) {
    boolean a = getSomeResult();
    if (a == true) {
        return "already saved";
    } 
    return "error exist";
}
Spring will use HTTP Message converters to convert the return value to HTTP response body [serialize the object to response body], based on Content-Type used in request HTTP header.
for more info:
http://websystique.com/springmvc/spring-mvc-requestbody-responsebody-example/
Controller part
You have to add the @ResponseBody annotation for spring ajax calls example
View Part
$.ajax({
    type : "GET",
    url : "${pageContext.request.contextPath}/check",
    data : {
        "id" : ${articleCount}
    },
    success: function(data){
        $('#input_field').val(data);
    }
});
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With