jQuery returning "parsererror" for ajax request jQuery returning "parsererror" for ajax request json json

jQuery returning "parsererror" for ajax request

I recently encountered this problem and stumbled upon this question.

I resolved it with a much easier way.

Method One

You can either remove the dataType: 'json' property from the object literal...

Method Two

Or you can do what @Sagiv was saying by returning your data as Json.

The reason why this parsererror message occurs is that when you simply return a string or another value, it is not really Json, so the parser fails when parsing it.

So if you remove the dataType: json property, it will not try to parse it as Json.

With the other method if you make sure to return your data as Json, the parser will know how to handle it properly.

See the answer by @david-east for the correct way to handle the issue

This answer is only relevant to a bug with jQuery 1.5 when using the file: protocol.

I had a similar problem recently when upgrading to jQuery 1.5. Despite getting a correct response the error handler fired. I resolved it by using the complete event and then checking the status value. e.g:

complete: function (xhr, status) {    if (status === 'error' || !xhr.responseText) {        handleError();    }    else {        var data = xhr.responseText;        //...    }}

You have specified the ajax call response dataType as:


where as the actual ajax response is not a valid JSON and as a result the JSON parser is throwing an error.

The best approach that I would recommend is to change the dataType to:


and within the success callback validate whether a valid JSON is being returned or not, and if JSON validation fails, alert it on the screen so that its obvious for what purpose the ajax call is actually failing. Have a look at this:

$.ajax({    url: '/Admin/Ajax/GetViewContentNames',    type: 'POST',    dataType: 'text',    data: {viewID: $("#view").val()},    success: function (data) {        try {            var output = JSON.parse(data);            alert(output);        } catch (e) {            alert("Output is not valid JSON: " + data);        }    }, error: function (request, error) {        alert("AJAX Call Error: " + error);    }});