225

Been getting a "parsererror" from jquery for an Ajax request, I have tried changing the POST to a GET, returning the data in a few different ways (creating classes, etc.) but I cant seem to figure out what the problem is.

My project is in MVC3 and I'm using jQuery 1.5 I have a Dropdown and on the onchange event I fire off a call to get some data based on what was selected.

Dropdown: (this loads the "Views" from the list in the Viewbag and firing the event works fine)

@{
    var viewHtmls = new Dictionary<string, object>();
    viewHtmls.Add("data-bind", "value: ViewID");
    viewHtmls.Add("onchange", "javascript:PageModel.LoadViewContentNames()");
}
@Html.DropDownList("view", (List<SelectListItem>)ViewBag.Views, viewHtmls)

Javascript:

this.LoadViewContentNames = function () {
    $.ajax({
        url: '/Admin/Ajax/GetViewContentNames',
        type: 'POST',
        dataType: 'json',
        data: { viewID: $("#view").val() },
        success: function (data) {
            alert(data);
        },
        error: function (data) {
            debugger;
            alert("Error");
        }
    });
};

The above code successfully calls the MVC method and returns:

[{"ViewContentID":1,"Name":"TopContent","Note":"Content on the top"},
 {"ViewContentID":2,"Name":"BottomContent","Note":"Content on the bottom"}]

But jquery fires the error event for the $.ajax() method saying "parsererror".

David East
  • 31,526
  • 6
  • 67
  • 82
dkarzon
  • 7,868
  • 9
  • 48
  • 61
  • does it fire a javascript error in the console or does the "error" handler function of the $.ajax() command get executed? – arnorhs Feb 21 '11 at 00:59
  • sorry, should have been more specific, it fires the $.ajax() error function { alert("Error"); } – dkarzon Feb 21 '11 at 01:08
  • Any chance of a live link? Do you see the JSON data you show in Firebug? – Pekka Feb 21 '11 at 01:12
  • No I dont have a live link. But yes that is the JSON response shown in Firebug. – dkarzon Feb 21 '11 at 01:17
  • yep, my bad was a typo. Fixed the question – dkarzon Feb 21 '11 at 04:27
  • @mu is too short - to be perfectly honest, 'javascript:' shouldn't be in there at all... – JAAulde Feb 21 '11 at 04:34
  • Probably not, was just tried a few things. But thats not the issue im having, the event is being fired correctly. – dkarzon Feb 21 '11 at 06:53
  • I'm also getting this issue with jQuery 1.7.2. Mine is a bit more complex though, as I'm attempting to use a ajaxPrefilter against a CORS resource. I suspect I'm having the same issue as this guy: http://bugs.jquery.com/ticket/12783 I'm only posting this here in case someone else is also getting this issue on the latest version of jquery while trying to parse valid JSON. – hendrikswan Jan 02 '13 at 09:47

19 Answers19

379

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.

Sastrija
  • 3,284
  • 6
  • 47
  • 64
David East
  • 31,526
  • 6
  • 67
  • 82
  • 6
    Thanks David, Method One worked for me. In my case I wasnt returning anything but used a datatype by mistake. Thanks for the tip. – Krishna Veeramachaneni Jun 11 '13 at 18:57
  • Thanks for the response, I have updated the answer for the quest as this seems like a better solution. – dkarzon Feb 18 '14 at 22:08
  • I encountered this problem when my php script had an error, and was returning non-JSON data - a useful suggestion to disable `dataType `indeed! – Sharadh May 14 '14 at 19:18
  • Thank you! This applies also to jquery.fileupload.js and other libraries using the JQuery AJAX methods. Confusing error message! – kqr Mar 31 '16 at 15:07
  • I am getting this issue using Rails jquery-ujs – Daniel Viglione May 05 '16 at 00:33
  • I used to set `dataType = ''` instead of removing it. – Hans Zimermann Oct 27 '17 at 19:40
  • The controller should have returned an http 204 status code instead of 200. In C# that is usually "return NoContent();" instead of "return Ok()". Then the datatype does not cause any issues and your own generic method can be used for queries that return data and those that do not return data. – Visual Micro May 11 '21 at 21:51
30

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;
        //...
    }
}
Community
  • 1
  • 1
johnhunter
  • 1,826
  • 15
  • 19
  • No ticket on this. Created a test case and I can only repeat the error firing when accessed with the file: protocol. So this is not the same issue. – johnhunter Feb 21 '11 at 17:46
  • Ok, so this sort of worked. Had to use an eval to remap the responseText to a Json object. Just seems strange that jQuery didnt work to parse the response... – dkarzon Feb 21 '11 at 23:10
  • @d1k_is glad it helped. Having to eval the responseText is a pain :( I filed a [ticket](http://bugs.jquery.com/ticket/8342) on this with JQuery. Turned out it has been fixed and will be in version 1.5.1. It may relate to your problem too. – johnhunter Feb 22 '11 at 09:44
  • 1
    Confirmed fixed in JQuery 1.5.1 – johnhunter Feb 25 '11 at 06:50
  • 13
    I have this problem in 1.7.2 :( – Eystein Bye Jun 22 '12 at 06:33
  • 7
    I was just having this problem, but I removed datatype: 'json' and the problem was solved. Since it is not returning a true form a json it will encounter a parser error. – David East Jul 16 '12 at 15:21
  • I'm hitting this in 1.7.2 as well. Removing dataType: jsonp isn't really an option, though, when you're using jsonp to handle a cross-domain situation – BrianFreud Aug 17 '12 at 01:09
  • 1
    The problem was fixed for me in 1.7.2 by adding dataType: "json", – NullVoxPopuli Aug 21 '12 at 14:24
  • 3
    I'm having this issue in 1.9.1, and I got around it by having my API return an empty hash `{}`. Shame this is necessary. – Adam Tuttle May 01 '13 at 14:03
  • 4
    This is actually in the documentation: `...The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected; the server should return a response of null or {} instead.` http://api.jquery.com/jQuery.ajax/ – Rob Sep 08 '13 at 22:41
  • 1
    -1: This answer is not a good fix, it's only a workaround and missing the root cause (which the comments and other answers like @David's describe). – Scott Stafford Oct 22 '13 at 15:14
  • This is infuriating because according to the spec, returning 204NoContent with... no content, is perfectly valid and fine yet jQuery insists its a server side flaw which is nonsensical. Not only that, but it's non-trivial or maybe impossible (I have yet to find a way) to modify the complete callback and indicate success instead of "parsererror". – Victorio Berra Apr 04 '18 at 17:08
24

You have specified the ajax call response dataType as:

'json'

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:

'text'

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);
    }
});
Nadeem Khan
  • 3,408
  • 1
  • 30
  • 41
12

the problem is that your controller returning string or other object that can't be parsed. the ajax call expected to get Json in return. try to return JsonResult in the controller like that:

 public JsonResult YourAction()
    {
        ...return Json(YourReturnObject);

    }

hope it helps :)

Sagiv Ofek
  • 25,190
  • 8
  • 60
  • 55
7

There are lots of suggestions to remove

dataType: "json"

While I grant that this works it's ignoring the underlying issue. If you're confident the return string really is JSON then look for errant whitespace at the start of the response. Consider having a look at it in fiddler. Mine looked like this:

Connection: Keep-Alive
Content-Type: application/json; charset=utf-8

{"type":"scan","data":{"image":".\/output\/ou...

In my case this was a problem with PHP spewing out unwanted characters (in this case UTF file BOMs). Once I removed these it fixed the problem while also keeping

dataType: json
Sam Strachan
  • 525
  • 5
  • 8
  • 1
    Agree with this... I checked the response and it was a var_dump() that was lost somwhere in the app. – Chuck Aug 13 '15 at 08:47
  • agree. Ich had a php deprecated warning in front of my json. I was using the firefox console to check the content and it FORMATTED the thing and took the error message out. The response looked fine. There's a switch to turn the formatting off.... – user3195231 Jul 28 '21 at 15:34
5

Your JSON data might be wrong. http://jsonformatter.curiousconcept.com/ to validate it.

Vishal Sakaria
  • 1,367
  • 1
  • 17
  • 28
2

Make sure that you remove any debug code or anything else that might be outputting unintended information. Somewhat obvious, but easy to forgot in the moment.

James John McGuire 'Jahmic'
  • 11,728
  • 11
  • 67
  • 78
0

I don't know if this is still actual but problem was with Encoding. Changing to ANSI resolved the problem for me.

0

If you get this problem using HTTP GET in IE I solved this issue by setting the cache: false. As I used the same url for both HTML and json requests it hit the cache instead of doing a json call.

$.ajax({
    url: '/Test/Something/',
    type: 'GET',
    dataType: 'json',
    cache: false,
    data: { viewID: $("#view").val() },
    success: function (data) {
        alert(data);
    },
    error: function (data) {
        debugger;
        alert("Error");
    }
});
Stuart
  • 1,227
  • 17
  • 21
0

you should remove the dataType: "json". Then see the magic... the reason of doing such thing is that you are converting json object to simple string.. so json parser is not able to parse that string due to not being a json object.

this.LoadViewContentNames = function () {
$.ajax({
    url: '/Admin/Ajax/GetViewContentNames',
    type: 'POST',
    data: { viewID: $("#view").val() },
    success: function (data) {
        alert(data);
    },
    error: function (data) {
        debugger;
        alert("Error");
    }
 });
};
Desi boys
  • 29
  • 3
0

incase of Get operation from web .net mvc/api, make sure you are allow get

     return Json(data,JsonRequestBehavior.AllowGet);
Community
  • 1
  • 1
Mohamed.Abdo
  • 2,054
  • 1
  • 19
  • 12
0

If you don't want to remove/change dataType: json, you can override jQuery's strict parsing by defining a custom converter:

$.ajax({
    // We're expecting a JSON response...
    dataType: 'json',

    // ...but we need to override jQuery's strict JSON parsing
    converters: {
        'text json': function(result) {
            try {
                // First try to use native browser parsing
                if (typeof JSON === 'object' && typeof JSON.parse === 'function') {
                    return JSON.parse(result);
                } else {
                    // Fallback to jQuery's parser
                    return $.parseJSON(result);
                }
            } catch (e) {
               // Whatever you want as your alternative behavior, goes here.
               // In this example, we send a warning to the console and return 
               // an empty JS object.
               console.log("Warning: Could not parse expected JSON response.");
               return {};
            }
        }
    },

    ...

Using this, you can customize the behavior when the response cannot be parsed as JSON (even if you get an empty response body!)

With this custom converter, .done()/success will be triggered as long as the request was otherwise successful (1xx or 2xx response code).

alexw
  • 8,468
  • 6
  • 54
  • 86
0

I was also getting "Request return with error:parsererror." in the javascript console. In my case it wasn´t a matter of Json, but I had to pass to the view text area a valid encoding.

  String encodedString = getEncodedString(text, encoding);
  view.setTextAreaContent(encodedString);
Laura Liparulo
  • 2,849
  • 26
  • 27
0

I have encountered such error but after modifying my response before sending it to the client it worked fine.

//Server side
response = JSON.stringify('{"status": {"code": 200},"result": '+ JSON.stringify(result)+'}');
res.send(response);  // Sending to client

//Client side
success: function(res, status) {
    response = JSON.parse(res); // Getting as expected
    //Do something
}
0

I had the same problem, turned out my web.config was not the same with my teammates. So please check your web.config.

Hope this helps someone.

Roshna Omer
  • 687
  • 1
  • 11
  • 20
0

I ran into the same issue. What I found to solve my issue was to make sure to use double quotes instead of single quotes.

echo "{'error':'Sorry, your file is too large. (Keep it under 2MB)'}";
-to-
echo '{"error":"Sorry, your file is too large. (Keep it under 2MB)"}';
user2402877
  • 33
  • 1
  • 6
0

When you are using dataType: 'json' your return type must be Json. You can use contentType: "application/json; charset=utf-8" rather than dataType: 'json'

100% correct

Saeid
  • 422
  • 4
  • 9
0

For me what fixes the issue was using returning Task<JsonResult> after serializing it:

[HttpPost, Route("GetSomeText")]
public async Task<JsonResult> GetSomeText(SomeRequest request)
{
    string result = "some text";
    return Json(JsonConvert.SerializeObject(result));
}
Koby Douek
  • 16,156
  • 19
  • 74
  • 103
-1

The problem

window.JSON.parse raises an error in $.parseJSON function.

<pre>
$.parseJSON: function( data ) {
...
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
...
</pre>

My solution

Overloading JQuery using requirejs tool.

<pre>
define(['jquery', 'jquery.overload'], function() { 
    //Loading jquery.overload
});
</pre>

jquery.overload.js file content

<pre>
define(['jquery'],function ($) { 

    $.parseJSON: function( data ) {
        // Attempt to parse using the native JSON parser first
        /**  THIS RAISES Parsing ERROR
        if ( window.JSON && window.JSON.parse ) {
            return window.JSON.parse( data );
        }
        **/

        if ( data === null ) {
            return data;
        }

        if ( typeof data === "string" ) {

            // Make sure leading/trailing whitespace is removed (IE can't handle it)
            data = $.trim( data );

            if ( data ) {
                // Make sure the incoming data is actual JSON
                // Logic borrowed from http://json.org/json2.js
                if ( rvalidchars.test( data.replace( rvalidescape, "@" )
                    .replace( rvalidtokens, "]" )
                    .replace( rvalidbraces, "")) ) {

                    return ( new Function( "return " + data ) )();
                }
            }
        }

        $.error( "Invalid JSON: " + data );
    }

    return $;

});
</pre>