Search code examples
javascriptajaxspring-bootjquery-ajaxq

Ajax post returning 404 even when the operation is successful


I am making an ajax post call to my backing spring controller. I see that the data is saved successfully in the db as a result of post but on the browser console I see that POST throws 404. Also, once the call returns from the spring controller, error function of ajax call is envoked.

Can someone please tell me what I am missing here.

$('#submitMessage').submit(function(e){
    e.preventDefault();
    var formData = {};
    var msg=document.getElementById('iconLeft4-1');
    var url = "${context}/wasadmin/support/ajax/send";
    formData['comment']=msg.value;
    formData['commented_by']='1';
    formData['supportId']='1';
    formData['userType']='O';
    console.log(JSON.stringify(formData));
    $.ajax({
        type : 'POST',
        contentType: "application/json",
        url : url,
        dataType : 'json',
        data:JSON.stringify(formData),
        success:function(data,status,xhr){
            console.log('saved successfully');

            },
        error:function(data,status,xhr){
            console.log('error occured');  // This gets  printed
            }

        });

Controller

@PostMapping(value="/ajax/send")
    public void sendSupportMessage(@RequestBody SupportConversationDTO supportConversationDTO) {
        supportConversationService.save(supportConversationDTO);
        return;
    }

Browser Console error


Solution

  • In your ajax request you are using dataType:'json', jQuery’s Ajax-Related Methods Description Says

    // The type of data we expect back
        dataType : "json",
    

    But from your controller, you are returning void!!!

    You need to update your ajax request, remove dataType and update success:function

    $.ajax({
        type : 'POST',
        contentType: "application/json",
        url : url,
        data:JSON.stringify(formData),
        success:function(data) {
            console.log('saved successfully');
        },
        error:function(data,status,xhr) {
            console.log('error occured');
        }
    });
    

    Then change your controller code, return something from it and add @ResponseBody

    @PostMapping(value="/ajax/send")
    @ResponseBody
    public String sendSupportMessage(@RequestBody SupportConversationDTO supportConversationDTO) {
        supportConversationService.save(supportConversationDTO);
        return "success";
    }