JSON.parse not erroring but not working - javascript

I am working on my webdesign assignment based around ajax. I am having a problem with the JSON.parse() function. The problem goes as follows, I perform a get request on my JSON database using ajax:
artist_list = $.ajax({
dataType: "json",
async: false,
method: "GET",
url: "/database/artists.json",
error: function (xhr) {
console.log("AJAX error:", xhr.status);
},
success: function(xhr, responseText) {
console.log("Ajax operation succseded the code was:", xhr.status);
console.log("This is the output", responseText);
response = responseText;
console.log("Parsing artist list");
JSON.parse(response);
console.log("Artist list parsed");
},
done: function(data, textStatus, jqXHR){
console.log("data:", data);
console.log("Response text",jqXHR.responseText);
}
})
The console log of the responseText matches what the JSON file I wanted but,
when I run response text through a for loop the log returns the JSON file char by char:
artist_list = artist_list.responseText;
JSON.parse(artist_list);
console.log(artist_list);
for(var i = 0; i < 1; i++) {
console.log("generating artist,", i);
console.log("which is:", artist_list[i]);
index = parseInt(i);
index = new artist_lite(artist_list[i]);
artist_lite_dict.push(index);
}
The console returns:
generating artist, 0
which is: {
The list is limited to one because of the lenght of the JSON object which I am trying to pass through. The JSON can be found here https://github.com/Stephan-kashkarov/Collector/blob/master/main/database/artists.json along with the whole code for testing purposes.
Thanks for your help!
- Stephan

You need to save the result of JSON.parse(artist_list); into some variable. I guess in your code you would like to solve it like this:
artist_list = JSON.parse(artist_list);

Related

How to parse this JSON result in Javascript?

I am trying to read this JSON that I get as a result of an AJAX get function. I seem to successfully get the data since when I console.log(result) I get the data in the console but I cannot seem to handle this result as a JSON object.
var isbnURL = "https://openlibrary.org/api/books?jscmd=data&format=json&bibkeys=ISBN:9780739332122"
$.ajax({
type: 'GET',
url: isbnURL,
dataType: 'json',
success: function(result){
console.log(result);
console.log(result.length);
},
error: function(message){
console.log(message);
}
});
I am expecting that console.log(result.length); returns the length and not undefined in the console.
The result of this is an object, not an array. Maybe you want to get, for example, the list of links inside the object. In this case you can do that:
result["ISBN:9780739332122"].links.length
var isbnURL = "https://openlibrary.org/api/books?jscmd=data&format=json&bibkeys=ISBN:9780739332122";
var isbnURL = "https://openlibrary.org/api/books?jscmd=data&format=json&bibkeys=ISBN:9780739332122";
$.getJSON({
url: isbnURL,
success: function(data) {
$.each(data, function(index, value) {
console.log("Small cover: " + value.cover.small);
console.log("Title: " + value.title)
});
}
});
This works. getJSON obtains the JSON and parses it, then the each function loops through each book.

Issue loading data into a dropdown via ajax

Encountering an issue loading a dropdown dynamically using JQuery AJAX.
The php is returning a valid JSON response. But when I attempt to load the data, I'm getting back either undefined, [object Object] or a single option with all my values comma separated. Nothing I've tried yields the correct answer.
This is the AJAX code block:
$.ajax({
type: "GET",
url:"data/getdata_codes.php",
dataType: "json",
success: function (data) {
alert("Success section");
alert(data);
$.each(data,function(key,value) <--Fails here
{
alert(key);
alert(value);
var option="<option value="+key+">"+value+"</option>";
alert(option);
$(option).appendTo('#myList');
});
},
error: function(xhr) {
alert("An error occured: "+ xhr.status + " " + xhr.statusText);
}
});
This is the JSON which is returned from the PHP, it validates.
{"data":[[{"0":"-1","CODE":"-1"}],
[{"0":"0","CODE":"0"}],
[{"0":"12","CODE":"12"}],
[{"0":"213","CODE":"213"}],
[{"0":"357","CODE":"357"}],
[{"0":"364","CODE":"364"}],
[{"0":"501","CODE":"501"}],
[{"0":"661","CODE":"661"}]]}
First of all your array is filled with arrays with 1 object. That makes it overly complicated.
Try something like this:
$(data.data).each(function(index, element) <- I guess your data variable also has a data attribute?
{
var array = element;
var objectInArray = array[0];
var key = objectInArray.0;
var value = objectInArray.CODE;
alert(key);
alert(value);
var option="<option value="+key+">"+value+"</option>";
alert(option);
$(option).appendTo('#myList');
});

JQuery Ajax limiting deep recursion "too much recursion"

The idea is that I send lots of synchronous requests to an API to create a JSON that I will need later to do some clusterizations. This API gives me information about articles, review etc. from a site (scopus.com). First I send a request based on a query from which I get a JSON which contains information about some articles. These articles are cited by other articles. I have to get information about these ones too so I need recursion. The problem is that I get an error because of "too much recursion". It seems that the error appears when the recursion is over and the program has to go back to the "root"/the first call. So the program will look like a very deep tree.
Pure Javascript does have this limitation too? What can I do?
Also I have to do SYNCHRONOUS requests otherwise the JSON I will get will be a mess.
EDIT:
I tested the script on queries that need a small recursion such as a tree with 4-5 levels.
var result = '{"entry":[ ';
function query(){
var results = getNumberResults();
if(results>0)
{
var pages = Math.ceil(results/25);
var i;
for(i=0; i<pages; i++){
$.when($.ajax({
url: url,
type: "GET",
async: false,
headers: {'Accept':'application/json'},
success: function(data){
$.each( data['search-results']['entry'], function( i, item ) {
get info from json and save it in my variable
if(data['search-results']['entry'][i]['citedby-count'] > 0)
getCitedBy(data['search-results']['entry'][i]['eid']);
else{
result += '"children-id":[]},';
}
});
}
}));
}
}
result = result.slice(0,-1);
result += "]}";
}
function getCitedBy(eid){
var results = getCitedByNumberResults(eid);
if(results>0)
{
var pages = Math.ceil(results/25);
var i;
for(i=0; i<pages; i++){
$.when($.ajax({
url: url,
type: "GET",
async: false,
headers: {'Accept':'application/json'},
success: function(data){
$.each( data['search-results']['entry'], function( i, item ) {
get info from json and save it in my variable
if(data['search-results']['entry'][i]['citedby-count'] > 0)
getCitedBy(data['search-results']['entry'][i]['eid']);
else{
result += '"children-id":[]},';
}
});
}
}));
}
}
}
function getNumberResults(){
var innerResult;
$.ajax({
url: url,
type: "GET",
async: false,
headers: {'Accept':'application/json'},
success: function(output){
innerResult = output['search-results']['opensearch:totalResults'];
},
error: function (xhr, ajaxOptions, thrownError) {
innerResult = 0;
}
});
return innerResult;
}
function getCitedByNumberResults(eid){
var innerResult;
$.ajax({
url: url,
type: "GET",
async: false,
headers: {'Accept':'application/json'},
success: function(output){
innerResult = output['search-results']['opensearch:totalResults'];
},
error: function (xhr, ajaxOptions, thrownError) {
innerResult = 0;
}
});
return innerResult;
}
The problem was as trincot mentioned and I also thought so was that 2 or more articles are referencing each other making an infinite cycle. I fixed it by searching my string variable for the unique identifier. So if in my variable already exists and article with that identifier I will skip recursion for the current article.
So I tested my script again for relative short queries (few hundreds of articles returned) because there are queries with huge outputs (millions of articles). When I will search for big queries I could come upon string size limitations(browser specific) or even “too much recursion”. If so I will let you know.
Advice: if “too much recursion” error occurs in your ajax request search first for an infinite cycle because this is the most probable cause.

jquery ajax fails to parse valid json

So I'm made a php script to output tweets in json and now I am trying to parse with data with javascript. I've tested the data and it's valid json. When I do the request in Example 2 it works fine. When I try to parse using example 1 it fails saying Uncaught SyntaxError: Unexpected token N. What is my problem?
Example 1
var request = $.ajax({
url: "http://website.com/twitter.php",
type: "GET",
data: {
twitter: 'google'
},
dataType: "json"
});
request.done(function(data) {
var resp = JSON.parse(data);
console.log(resp);
});
request.fail(function(jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
Example 2
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://website.com/twitter.php?twitter=google", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var resp = JSON.parse(xhr.responseText);
console.log(resp);
}
};
xhr.send();
JSON Data
["New Google Trends features\u2014including Trending Top Charts\u2014make it easier to explore hot topics in #GoogleSearch g.co\/jmv6","Stating now, join our Hangout w\/ President Barroso on the #SOTEU goo.gl\/FZCXaJ #askbarroso","Explore the Galapagos Islands + see sea lions, blue-footed boobies & other animals w\/ Street View in #googlemaps g.co\/ufjq","Slow connections may keep Google Instant (results as you type) from working smoothly. Our troubleshooting tip: g.co\/bve7","From #BBCNews: search VP Ben Gomes on how search has become more intuitive & the next frontier (includes video) goo.gl\/Z0ESkJ","\"Audio Ammunition\" - an exclusive 5-part documentary about the Clash from #GooglePlay g.co\/zrxn & on youtube.com\/googleplay","justareflektor.com\u2013\u2013an interactive #ChromeExp HTML5 film with #arcadefire, featuring their new single, \u201cReflektor\u201d","#askbarroso about the State of the European Union in a live conversation Thurs, Sept 12 g.co\/n3tj","Don\u2019t get locked out: set up recovery options for your Google Account now g.co\/sm4k","It's time for more transparency: our amended petition to the the U.S. Foreign Surveillance Court g.co\/gkww"]
Since you have json as your data type, data in your done callback will already be parsed so trying to parse it again is causing the error.
request.done(function(data) {
//var resp = JSON.parse(data);
console.log(data);
});
jQuery's .ajax automatically parses the JSON response, so .parse shouldn't be called separately. Use the following:
$.ajax({
url: "http://example.com/twitter.php",
type: "GET",
data: {
twitter: 'google'
},
dataType: "JSON",
success : function(JSON,jqXHR){
console.log(JSON.value); /* value of value */
console.log(jqXHR.responseText); /* all returned */
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert("Request failed: " + textStatus);
}
});

Getting typeError:e is undefined in firebug while running a script

I am not able to figure out what is wrong with my code.I am getting data from post as an array and I am then displaying that data in box.
function worker() {
var a = $("#BeeperBox");
var delay =2000;
$.ajax({
url: '/index.php/admin/getLatest',
success: function(data) {
$.each(data.upda,function(i, v){
var out = v.name + v.mob ;
$('span.blueName').html(out);
$("#BeeperBox").show();
timerId = setTimeout(function () {
a.hide();
}, delay);
});
},
complete: function() {
// Schedule the next request when the current one's complete
setTimeout(worker, 50000);
}
});
}
When i run it firebug shows error: TypeError: e is undefined.
since your sending the response as JSON.. its better to specify your dataType as JSON (though If none is specified, jQuery will try to infer it based on the MIME type of the response ) so that you don't have to parse it manaully..i think the problem here is you havn't parsed the json that you got as response
try this
$.ajax({
url: '/index.php/admin/getLatest',
dataType: 'json',
success: function(data) {
$.each(data.upda,function(i, v){
var out = v.name + v.mob ;
......
},
Check if data.upda is undefined, I think the problem is that that variable doesn't exist and you're trying to iterate over a undefined element.

Categories