Home > Software design >  Ajax error getting called instead of success
Ajax error getting called instead of success

Time:07-11

<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:

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)

CodePudding user response:

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',
  • Related