Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Ajax error getting called instead of success

<script>
        function editComment(id) {
            var content = $('#Content').val();
            var modelData = { 'Id': id, 'Content': content };
            $.ajax({
                type: 'POST',
                dataType: 'json',   
                url: '@Url.Action("EditC", "Comment")',
                data: JSON.stringify({ model: modelData }),
                contentType: 'application/json',
                success: function () {
                    alert("YES");
                },
                error: function () {
                    alert("Error");
                }
        });
        }
    </script>

Here the server is returning 200 OK, but for some reason the error function is getting called. Both type and contentType seem to be correct. Any idea how to fix this?

Edit:
After adding

error: function (xhr, textStatus, error) {
                    console.log(xhr.responseText);
                    console.log(xhr.statusText);
                    console.log(textStatus);
                    console.log(error);
                }

this is what is being logged:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

parsererror
parsererror
SyntaxError: Unexpected end of JSON input
    at parse (<anonymous>)
    at ajaxConvert (jquery-3.4.1.js:9013:19)
    at done (jquery-3.4.1.js:9483:15)
    at XMLHttpRequest.<anonymous> (jquery-3.4.1.js:9785:9)

>Solution :

Moving to an answer for future readers…

The server is indeed returning a successful response, but an empty successful response:

return new HttpStatusCodeResult(200);

However, the client-side code is expecting valid JSON:

dataType: 'json',

As a result, after the successful response is received, internally the jQuery code attempts to parse that response as JSON and that fails, resulting in triggering the error callback.

Since there’s no response body (and in most cases even when there is, as long as the server returns the correct MIME type), you don’t need or want to specify a dataType in the jQuery AJAX operation. Simply remove this part:

dataType: 'json',
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading