Jose Luis Arrondo
Jose Luis Arrondo

Reputation: 33

Spring MVC Ajax call POST not working

I have a form which I convert into an object. I wanna pass that object onto the server, a GET ajax request works fine but the object is empty in the java method, then I do the very same request but a POST request and it says error 404. Not sure what I'm doing wrong or what is, followed many examples, but neither of them seem to work.

GET REQUEST

(Ajax call)

$.ajax({
     type: "GET",
     url: "/pp/portal/" + businessId64 + "/saveMedicalQuestionnaire",
     contentType: 'application/json',
     dataType: 'json',
     data: { medicalHistoryDTO : medicalHistoryDTO },
     success: function(data) {
            console.log(data);
     }
});

(Object medicalHistoryDTO)

Object

(Java Method)

@RequestMapping(value="/*/saveMedicalQuestionnaire", method = RequestMethod.GET)
public @ResponseBody String postEditMedical(MedicalHistoryDTO medicalHistoryDTO)
{
    System.out.println("COMMON CONTROLLER POSTEDITMEDICAL SAVE MEDICAL QUESTIONNAIRE");
    System.out.println(medicalHistoryDTO);

    return "WORKING FINE";  
}

(Eclipse console)

COMMON CONTROLLER POSTEDITMEDICAL SAVE MEDICAL QUESTIONNAIRE
MedicalHistoryDTO [list=null, medicalHistorySignature=null]

(Browser console) enter image description here

POST REQUEST

(Ajax call)

$.ajax({
     type: "POST",
     url: "/pp/portal/" + businessId64 + "/saveMedicalQuestionnaire",
     contentType: 'application/json',
     dataType: 'json',
     data: { medicalHistoryDTO : medicalHistoryDTO },
     success: function(data) {
            console.log(data);
     }
});

(Java Method)

@RequestMapping(value="/*/saveMedicalQuestionnaire", method = RequestMethod.POST)
public @ResponseBody String postEditMedical(MedicalHistoryDTO medicalHistoryDTO)
{
    System.out.println("COMMON CONTROLLER POSTEDITMEDICAL SAVE MEDICAL QUESTIONNAIRE");
    System.out.println(medicalHistoryDTO);

    return "WORKING FINE";  
}

(Browser console)

enter image description here

Upvotes: 0

Views: 2700

Answers (2)

shakeel
shakeel

Reputation: 1695

Keep using POST and to recieve you need to use @RequestBody tag

public @ResponseBody String postEditMedical(@RequestBody MedicalHistoryDTO medicalHistoryDTO)

You can see a working example from my code to https://github.com/shakeelabbas1/webservice/blob/master/src/main/java/com/service/controller/ServiceRequestController.java

Update: I also see data: { medicalHistoryDTO : medicalHistoryDTO } Replace it with data: medicalHistoryDTO

Upvotes: 1

Jungle
Jungle

Reputation: 107

try to specify path more strictly

@RequestMapping(value="/{id}/saveMedicalQuestionnair", , method = RequestMethod.POST)
public @ResponseBody
String postEditMedical(MedicalHistoryDTO medicalHistoryDTO, @PathVariable("id") int id)

Upvotes: 0

Related Questions