jQuery.ajax() + empty JSON object = parse error - javascript

I get a parse error when using jQuery to load some JSON data. Here's a snippet of my code:
jQuery.ajax({
dataType: "json",
success: function (json)
{
jQuery.each(json, function ()
{
alert(this["columnName"]);
});
}
});
I get no errors when parsing a non-empty JSON object. So my guess is that the problem is with my serializer.
Question is: how do I format an empty JSON object which jQuery won't consider malformed?
This is what I've tried so far, with no success:
{[]}
{[null]}
{}
{null}
{"rows": []}
{"rows": null}
{"rows": {}}
UPDATE:
I can understand that I've been somewhat vague--let me try and clarify:
Parsing of the JSON object is not the issue here--JQuery is - I think.
jQuery throws a parse-error (invokes the error function). It seems like jQuery's internal JSON validation is not accepting any of the before mentioned objects. Not even the valid ones.
Output of the error function is:
XMLHttpRequest: XMLHttpRequest readyState=4 status=200
textStatus: parsererror
errorThrown: undefined
This goes for all of the before mentioned objects.

The solution is to return a status code of 204 rather than 200 from the server, 204 is "no content" and it will return success while not trying to invoke the parser

Firstly {[]}, {[null]}, and {null} won't work because they are all invalid JSON objects (as verified by the JSON validator).
The remaining objects are all valid JSON objects, so your success function should be getting invoked.
If you pass a non-array or array-like object object then the each function will enumerate your json object by its named properties. In the case of your three objects that each have a rows property this will be set to [], null, and {} respectively, none of which have a columnName attribute so an undefined error will be thrown.
Your {} object on the other hand has no properties, so shouldn't be causing an error because the each call will loop 0 times. What does the following line display if you add it as the first line in your success function?
alert(typeof json + ' ' + (json == null));

you are looking for this:
[]
an empty array. That is, if you plan to iterate over it right away, then what you need is an array.

Your web service may be returning null. I've found that returning null from a web service call returns a response with status code 200, "Ok", but jQuery throws a parseerror afterwards.
If this is the case, it has nothing to do with what you're sending up to the server, and everything with what the server is sending back.
If you're able to change the web service, you might want to try returning an empty JSON object, or a default value instead of Null. Alternatively, you could check for this error scenario in your error handler, knowing that this means your call returned null.

Did you verify if the JSON is returned correctly in the first place before the each? Set the empty value as {}, and verify if it is like that before .each
Also it would help to know how your JSON looks like when there is data.

Instead of:
$(json).each(function () { ... });
I think you want to be using:
$.each(json, function () { ... });
From the jQuery.each documentation:
This function is not the same as
$().each() - which is used to iterate,
exclusively, over a jQuery object.
This function can be used to iterate
over anything.

I was experiencing similar problems when requesting valid JSON from the server.
My server was serving the content-type of text/javascript
I was not using the optional jQuery.ajax setting of 'dataType' so jQuery was interpretting the output a javascript (eg padded JSON), not neat JSON.
Adding a dataType:'JSON' to the settings object passed to jQuery's ajax method solved the problem.

Had this problem as well, and solved it by using the jsonserializer in my web service to format an empty string. result is was "\"\"" essentially "" ;

Related

Javascript access element from return value of ajax call in JSON

So I make an ajax call that does return successfully but the problem is that I cannot access individual elements of the array it returns, meaning I can't console log it. It returns either error or undefined. Error would be like track is not defined but when you look at the example ajax return, track is there. Here is the code
$.ajax({
url: 'https://api.spotify.com/v1/playlists/'+playlist+'/tracks?fields=items(track.id)',
headers: {
'Authorization': 'Bearer ' + access_token
},
success: function(response,access_token) {
Result(response,access_token);
},
dataType:"json"
});
function Result(response,access_token){
console.log(response[0].track.id);
console.log(response[0]);
console.log(response.track);
}
The ajax call returns an array that looks like this for example. Inspecting an individual element.
items: Array(80)
-0:
-track:
-id: "Random String"
I read up on JSON methods and how it handles arrays and when I console logged response[0].track.id I believe I should see the id string. I also tried different console logs as well but have omitted because they all have the same kind of errors. I am trying to do this cause at one point I might put these ids in their own array and will need to add each individual element one at a time for further use. Thank you for any assistance and let me know if you need more details.
From the inspected value... it looks like you should check response.items[0].track.id instead...

Filter JSON response on a jQuery ajax request, for XSS text

I am falling into a silly issue where the server is giving JSON response with XSS safe text added.
The server gives only 2 kinds of response:
HTML page with hidden input field that contains the value I want
JSON String with the value which can be preferably converted to JS
Object.
The problem is, for preventing JavaScript XSS attacks, the JSON response is made like this:
while(1);{
"name": {
"abc": "123",
...
}
}
So this goes to parseerror in jQuery ajax method and therefore in the error callback.
How do I fix this?
Also, I tried putting a hook in the error function and change the JSON data:
error: function(jqXHR) {
removeJSCode (jqXHR.responseText);
}
// ...
function removeJSCode(json) {
.. Code to filter the response
}
But this does not work.
jQuery's $.ajax has dataFilter property in its configuration. Pass it a function and it runs after jQuery receives ajax data, but before jQuery has a chance to touch it.
The function is provided the string response as first argument and data type as second argument. The second argument will depend if you passed dataType in the configuration.
There, you can use .replace('while(1);','') and return the string from the function for jQuery to parse.
$.ajax({
...
dataType : 'json',
dataFilter : function(response,type){
//if not JSON, don't do anything with it
if(type !== 'json') return response;
//otherwise, replace and return
return response.replace('while(1);','');
}
...
});

I dont get any data from the getJSON function

I am trying to get a JSON object from a .jsp page. But I dont know what to do with it. I've googeled this for some time now, but I can't find out what this getJSON functions does.
Does it return a string representation of a JSON object?
Or is the parameter 'json' that is passed into the function the JSON Object?
Is the function (the second parameter) equivalent to the function that one write when using XMLHttpRequests? In other words; is this function the asynchronous part?
The alert with "JSON stuff" doesnt print.
<script type="text/javascript" src="jquery-1.7.2.js"></script>
<script type="text/javascript">
function checkUni() {
var URL = "http://localhost:8080/GradSchoolApp/test.jsp";
var jso = $.getJSON(URL, function(json) {
alert("JSON stuff " + json.name);
});
alert(jso);
//alert(jso.name);
}
A few things to check:
Is the webapp also running at localhost:8080? If not, you might be running afoul of the same origin policy, in which case you would need to encode to jsonp.
You should also check in firebug/inspect element/whatever to make sure you are actually getting something returned from your request. You can do this in the network or resources tab depending on which browser you are using. Also stick a breakpoint in your script before the alert and inspect the json object to see if anything was returned.
The second alert isn't firing because the json object doesn't exist yet when you call it.
The relevant docs for getJSON is here. The callback parameter (that you named json) is the already decoded data (i.e. it's a JavaScript object, not a string).
As for why your alert isn't doing anything, see Charles Bandes's answer. To better debug your code you can also use console.log (will work on Firebug or on Chrome), and/or set a handler to ajaxError - so if the problem is with your request you can be notified of the error (instead of the browser ignoring it by default).
Does it return a string representation of a JSON object?
The respone will come as JSON format. getJSON method is a short form of jQuery ajax with datatype as json . The datatype decides what is the format to receive the result from the ajax call.
is the parameter 'json' that is passed into the function the JSON
Object?
The variable json in your callback function will get the response from your ajax call. The data should in a valid JSON Document( if your server pages returns like that properly)
is this function the asynchronous part?
As i told you earlier, getJSON is a shortform of jquery ajax with datatype as Json. It is asynchronous.

JSON.parse works but jQuery.getJSON returns http error 403

When I use JSON.parse(jsonString), the JSON is parsed no problem at all.
var result = JSON.parse(jsonString);
But when I use jQuery.getJSON(jsonString) i received an http error 403.
var result = jQuery.getJSON(jsonString);
Any idea why one will work and the other will not? They are both reading a string.
Thanks!
They are both reading a string.
Oh no! Those two methods are so very much different. They have absolutely nothing in common. They are accomplishing 2 entirely different tasks.
The first simply parses a JSON string into a javascript object:
var result = JSON.parse('{"foo": "bar"}');
alert(result.foo);
will show bar. Also notice that the JSON.parse method is a built-in method in modern browsers. It's pure javascript and has strictly nothing to do with jQuery. Legacy browsers do not support it. For them you need to include the json2.js script to your page.
The second performs an AJAX call and expects as argument an url:
jQuery.getJSON('/someserversidescript', function(result) {
// callback to be executed when the AJAX request succeeds
});
As you can see here the argument is an url. Calling jQuery.getJSON('{"foo": "bar"}') makes strictly no sense. I guess that's the reason why your server responds with 403 error, since this is not valid url on your server. It expects that the server will return a JSON string as response. It's simply a shorthand for:
$.ajax({
url: '/someserversidescript',
type: 'GET',
dataType: 'json',
success: function(result) {
// callback to be executed when the AJAX request succeeds
}
});
getJSON() is an asynchronous call back to a server that returns a JSON object. JSON.parse() takes a string and returns a JSON object in memory. They are completely different.

Invalid Label Error with JSON request

I've read about this a lot and I just can't figure it out. It has nothing to do with MY code, it has to do with the feed or something because if I swap it with a Twitter feed it returns an Object object which is perfect.
$.getJSON('http://rockbottom.nozzlmedia.com:8000/api/portland/?count=1&callback=?',function(json){
console.log(json)
});
And i get an "invalid label" error. Any ideas?
Also, a side note, I've tried the AJAX method as well:
$.ajax({
url: 'http://rockbottom.nozzlmedia.com:8000/api/portland/',
dataType: 'jsonp',
data: 'count=1',
success: function(msg){
console.log(msg)
}
});
and both give the same exact error, and both work fine with Flickr and Twitter examples, so it must be something to do with the feed, but I dont have access to the feed, but I could ask them to fix something IF it's their issue.
Make sure that the server side can handle the JSONP request properly. See here for example.
Edit: It seems that the server doesn't wrap the returned JSON object with the callback function name. The server should return:
callback( { json here } )
and not
{ json here }
That URL looks like it's expecting you to provide a JSONP callback (from the callback=? bit). That's probably the problem; it's returning Javascript rather than JSON (because that's how JSONP works). See the $.ajax docs for more about using JSONP services.
The returned content has unescaped double-quotes in one of the strings. It's invalid JSON:
..."full_content":"just voted "with Mandy " on...

Categories