Nahid Shah Nahid Shah - 1 year ago 70
Ajax Question

Having difficulties sending data from ajax to spring mvc controller

My ajax code looks like this:

function GetProjectlist() {
var obj = { department : department};
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);"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.

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

                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