Nahid Shah Nahid Shah - 1 year ago 52
Ajax Question

Having difficulties sending data from ajax to spring mvc controller

My ajax code looks like this:

function GetProjectlist() {
alert(department);
var obj = { department : department};
$.ajax({
type: "POST",
url: "http://localhost:8080/MyApplication/getAllProjects",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnGetProjectSuccess,
error: OnGetProjectError
});
}


On the other hand my Controller looks like this:

@RequestMapping(value = "/getAllProjects", method = RequestMethod.POST,headers = {"Content-type=application/json"})
public @ResponseBody JsonJtableProjectListResponse getAllProjects(@RequestParam(value = "department", required = false) String department) {

System.out.print("department"+department);
logger.info("Home Controller -getAllProjects");


..................................................

When I print department in the controller it is null. Can anyone tell me how I can pass department from ajax to controller?

Answer Source

Try using @RequestBody annotation instead of @RequestParam annotation since you are sending json data. Check this article about how to do it.

http://hmkcode.com/spring-mvc-json-json-to-java/

For simple param passing, use something like below and use @RequestParam on server side like you had earlier.

$.ajax({
                type: "GET",
                url:  "http://localhost:8080/MyApplication/getAllProjects",               
                data: {department:department},
                dataType: "json",
                success: OnGetProjectSuccess,
              error: OnGetProjectError
            });
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download