Ajax request throwing a 404 error despite the successful completion of the operation

I've encountered an issue while making an ajax post call to my Spring controller. The data is successfully saved in the database, but I'm seeing a 404 error on the browser console when the POST request is made. Additionally, once the call returns from the controller, the error function of the ajax call is triggered.

Could someone please point out what might be 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;
    }

https://i.sstatic.net/krgNi.jpg

Answer №1

When making an ajax request, ensure that your dataType matches the data type being returned from the controller. Check out jQuery’s Ajax-Related Methods for more information.

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

If your controller is returning void, update your ajax request accordingly by removing the dataType and adjusting the 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');
    }
});

Make sure to modify your controller code as well by having it return a value and adding @ResponseBody.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Access a single document from Firestore:

How can I fetch a single document from Firestore in Angular 4? I am not looking for a list of documents in the collection, I already know how to do that. Let's say I have a key-value pair of the document and I want to retrieve it using Angular 4. i ...

Problem with APIGEE search function

Encountered an issue while trying to retrieve an Apigee collection using the following code snippet: var my_pc_list = new Apigee.Collection( { "client":client, "type":"pc_pedidos", qs :{ql:"limit:50"} }); Error details: {"error":"query_parse","timestamp ...

After the update to Angular 9, the stopImmediatePropagation function on mat-expansion-panel is no longer functioning as

Issue Description After upgrading to Angular 9, the expected behavior of preventing an expansion panel from opening when editing a field inside was not working. The use of event.stopImmediatePropagation() and event.stopPropagation() did not prevent the exp ...

Utilizing JSON for seamless integration of FullCalendar into Joomla component

I am currently working on integrating FullCalendar with my Joomla component by writing a JSON feed in the controller: public function getAvails() { $app = JFactory::getApplication(); $document = JFactory::getDocument(); $admin_id = $ ...

Issue with Angular Promise ($q) functionality being non-operational

I am currently experimenting with integrating Angular and SignalR in a demo application. I have attempted to implement promises using the $q service, but for some reason my code is not functioning as expected. SERVICE var boardConsole = $.connection.buil ...

Error: Unable to access the 'questionText' property as it is undefined

I encountered an error message stating that my "questionText" could not be read or is not defined. The issue seems to arise in the first code block where I use "questionText", while the intention is to drag it in the second code block. Is there a mistake ...

The clear icon in React will only appear when there is a value inputted

Is there a way to implement the clear X icon that only appears when typing in the input field using reactjs, similar to the search input on the Google homepage? Check it out here: https://www.google.com import { XIcon } from '@heroicons/react/solid&ap ...

A step-by-step guide on developing template tags in the express framework inspired by Django

Can template tags similar to Django's be created in Node.js using the Express framework? Thank you, ...

Having difficulty formatting text alignment using CSS

Is there a way to maintain the alignment of text in the output of the 'About' section even when the content changes dynamically? I want the new line to appear just below 'Lorem', but currently, it shifts below the colon(:). Since the le ...

When you hover over an image, both the image's opacity and the color of the title beneath it change. However, if the title expands to two lines, it messes up

I am currently working on a project where I have an image and a title displayed below the image. My goal is to change the color of the text when hovering over the image, as well as adjust the opacity of the image. Additionally, when hovering over the title ...

The state is not being configured accurately

In my ReactJs project, I have a model Component with a picture that is displayed. I want to pass the data of the clicked picture, which can be neither raw data nor a URL. I have implemented a handler that can delete the picture (if pressed with the Ctrl k ...

Transform array sequences into their own unique sequences

Reorder Array of List to Fit My Custom Order Current Output: [ { "key": "DG Power Output", "value": "6.00", "unit": "kWh", }, { "key": "DG Run Time", "value": "5999999952", "unit": "minutes", }, { "key": "Fuel Level (Before)", "value": "8.00" ...

What is the best way to pass the ng-repeat value to the controller in AngularJS

On my webpage, I am trying to utilize ng-repeat with an array like the one below: var array = [{name: Bill, age: 12, number: 1}, {name: Tyrone, age: 11, number: 2}, {name: Sarah, age: 14, number: 3}]; I want to have a button that, when clicked, sends eit ...

Optimize Page Speed by Delaying the Loading of Slideshow Images

My main issue with reducing my pagespeed is the slideshow I have implemented. I currently have 17 rather large images in the slideshow, but for simplicity, I will only show the code for 3 images below. I am trying to find a way to load the first image as a ...

Storing JavaScript code in a PHP variable fails to function

I've encountered an issue with my JavaScript code. <script> $(document).ready(function(){ $('.delete').click(function() { alert('passed'); }); }); </script> Everything work ...

What is the best way to animate changes to a background image using jQuery?

Exploring the possibilities of creating a unique visual effect reminiscent of a pulsing heartbeat for a button. I'm under the impression that achieving this is beyond the scope of CSS. Can anyone shed light on how to implement an animated background ...

Getting the value of elements with the same id in JavaScript can be achieved by utilizing the getElement

When I click on the first delete link, I want to display the value from the first input box. Similarly, when I click on the second delete link, I want to show the value from the second input box. Currently, it is always showing the value from the first del ...

Having trouble with the open and create new post button not functioning properly

The submit post button, user name, and logout button are not functioning properly. Can anyone assist with this issue? F12 and jsintrc are not providing any useful information. Below is the HTML code for the create new post button which should direct to a ...

Problems with Ajax calls are preventing Internet Explorer9 and Internet Explorer10 from functioning properly

I am facing an issue with displaying item pages using Ajax. The function works perfectly in Chrome, but not in Internet Explorer. <script type="text/javascript"> function obtainInfo(str) { if (str=="") { document. ...

The video is unavailable due to issues with ImageKit

In my project, I am incorporating ImageKit into the workflow. Currently, I have set up a basic process that only includes the video upload feature. On the backend, I have a lone file named index.js. I haven't developed a frontend yet, so I have been e ...