jQuery returning "parsererror" for ajax request
Solution 1
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.
Solution 2
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;
//...
}
}
Solution 3
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);
}
});
Solution 4
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 :)
Solution 5
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
Related videos on Youtube
Comments
-
dkarzon almost 3 years
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".
-
Julio Faerman about 13 yearsdoes it fire a javascript error in the console or does the "error" handler function of the $.ajax() command get executed?
-
dkarzon about 13 yearssorry, should have been more specific, it fires the $.ajax() error function { alert("Error"); }
-
Pekka about 13 yearsAny chance of a live link? Do you see the JSON data you show in Firebug?
-
dkarzon about 13 yearsNo I dont have a live link. But yes that is the JSON response shown in Firebug.
-
dkarzon about 13 yearsyep, my bad was a typo. Fixed the question
-
JAAulde about 13 years@mu is too short - to be perfectly honest, 'javascript:' shouldn't be in there at all...
-
dkarzon about 13 yearsProbably not, was just tried a few things. But thats not the issue im having, the event is being fired correctly.
-
hendrikswan over 11 yearsI'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: 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.
-
-
johnhunter about 13 yearsNo 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.
-
dkarzon about 13 yearsOk, 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...
-
johnhunter about 13 years@d1k_is glad it helped. Having to eval the responseText is a pain :( I filed a ticket 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 about 13 yearsConfirmed fixed in JQuery 1.5.1
-
dkarzon almost 13 yearsSorry, forgot to include my codebehind, but thats exactly how the Json is returned.
-
Eystein Bye almost 12 yearsI have this problem in 1.7.2 :(
-
David East almost 12 yearsI 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.
-
BrianFreud over 11 yearsI'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
-
NullVoxPopuli over 11 yearsThe problem was fixed for me in 1.7.2 by adding dataType: "json",
-
Adam Tuttle about 11 yearsI'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. -
Krishna Veeramachaneni almost 11 yearsThanks David, Method One worked for me. In my case I wasnt returning anything but used a datatype by mistake. Thanks for the tip.
-
Rob over 10 yearsThis 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.
api.jquery.com/jQuery.ajax -
Scott Stafford over 10 years-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).
-
dkarzon about 10 yearsThanks for the response, I have updated the answer for the quest as this seems like a better solution.
-
Sharadh almost 10 yearsI encountered this problem when my php script had an error, and was returning non-JSON data - a useful suggestion to disable
dataType
indeed! -
Chuck over 8 yearsAgree with this... I checked the response and it was a var_dump() that was lost somwhere in the app.
-
kqr about 8 yearsThank you! This applies also to jquery.fileupload.js and other libraries using the JQuery AJAX methods. Confusing error message!
-
Daniel Viglione almost 8 yearsI am getting this issue using Rails jquery-ujs
-
Hans Zimermann over 6 yearsI used to set
dataType = ''
instead of removing it. -
Victorio Berra about 6 yearsThis 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".
-
Alexander almost 6 yearsor remove the datatype :)
-
MinionAttack over 4 yearsThank you, method 1 was my solution!
-
Visual Micro almost 3 yearsThe 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.
-
andy almost 3 yearsThe OP actually uses double quotes, does he?
-
user3195231 almost 3 yearsagree. 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....