How to parse this JSON result in Javascript? - 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.

Related

How can I capture the Array object returned by an api call through HTTP GET?

The API call
https://myhost.net/api/get_global_search_result/methods/test
returns an Array object. I am trying to hold it in an Array object in order to read the attributes and values in it.
var queryResult = [];
queryResult = browser.get('https://myhost.net/api/get_global_search_result/methods/test/');
console.log('result length: ' + queryResult.length);
This is what I see on my console:
result length: undefined
If I load the above specified URL directly in a browser instance, it shows the Array with its contents.
What is the better way of capturing the array object returned by this call?
What about using JQuery ajax request.
it would be some thing like :
$(document).ready(function() {
$("#testbutton").click(function() {
$.ajax({
url: 'http://localhost:9200/xyz/xyz/xfSJlRT7RtWwdQDPwkIMWg',
dataType: 'json',
success: function(data) {
alert(JSON.stringify(data));
},
error: function() {
alert('error');
}
});
});
});

get variable from json response

I have a GET function and response in JSON.
This is function:
$.ajax({
contentType: 'application/json',
dataType: 'json',
success: function(msg){
var result = JSON.stringify(msg);
console.log(result);
},
error: error,
type: 'GET',
url: myurl
});
success response from result is like this:
{"response":{"values":[{"name":"john","sex":"male"}]}}
But when I try to get the name from response, I get an error!
This is the error:
for(var k in result){
console.log(result[k]);
}
displays the letters
I tried this:
$.each(result,function(index, value){
console.log(index, value);
});
but always get error.
Try removing the JSON.stringify(msg.response). After which, msg.response.values[0].name
should givejohn
The response that you are getting is itself a json object.You can iterate through the object and get the name from the object.
You can access the value from json itself
var response = {"response":{"values":[{"name":"john","sex":"male"}]}};
var getName = response.response.values[0].name;
alert(getName);

JavaScript Saving data from an ajax request

Challenge:
While on URL1(random wikipedia page), make an ajax request to URL2(100 most common words wikipedia page), format a list out of the returned data to be used later.
I have to run this from the console while on "URL1"
example:
Navigate to URL1
Open Console
paste code
hit enter
So far I have been able to grab the entire html source while on URL1 with the following:
$.ajax({
url: 'https://en.wikipedia.org/wiki/Most_common_words_in_English',
type: 'GET',
dataType: 'html',
success: function (response) {
console.log(response); // works as expected (returns all html)
}
});
I can see in the console the entire HTML source -- I then went to URL2 to figure out how to grab and format what I needed, which I was able to do with:
var array = $.map($('.wikitable tr'),function(val,i){
var obj = {};
obj[$(val).find('td:first').text()] = $(val).find('td:last').text();
return obj;
});
console.log(JSON.stringify(array));
Now this is where my issue is -- combining the two
$.ajax({
url:'https://en.wikipedia.org/wiki/Most_common_words_in_English',
type:'GET',
dataType:'html',
success: function(data){
// returns correct table data from URL2 while on URL2 -- issue while running from URL1
var array = $.map($('.wikitable tr'),function(val,i){
var obj = {};
obj[$(val).find('td:first').text()] = $(val).find('td:last').text();
return obj;
});
console.log(JSON.stringify(array));
};
});
Im guessing this is due to the HTML I want to map is now a string, and my array is looking for HTML elements on the current page which it of course would not find.
Thanks
Simple fix here! You're exactly right, it's not parsing the html you return, so just tell jQuery to convert it into an object it can use $(data) and use that to find what you need.
In essence, your 'document' now becomes $(data) which you will use as the source of all your queries.
$.ajax({
url: 'https://en.wikipedia.org/wiki/Most_common_words_in_English',
type: 'GET',
dataType: 'html',
success: function(data) {
var myVar = data;
Names = $.map($(myVar).find('.wikitable tr'), function(el, index) {
return $(el).find('td:last').text()
});
console.log(Names);
}
});

GeoJson "Not Well Formed" message in console, and appears undefined

Ive included the very end of my script below, where I'm trying to put a JSON file into a website using Ajax callback function. When I inspect the page, I'm seeing that the JSON file is not well formed and I can't seem to find an answer. The webpage is also just showing that the JSON file is "undefined".
function debugCallback(response){
var mydata;
$("#mydiv").append('GeoJSON data: ' + JSON.stringify(mydata));
};
function debugAjax(){
var mydata;
$.ajax("data/MegaCities.GeoJSON", {
dataType: "json",
success: function(response){
//mydata = response;
debugCallback(mydata);
}
});
$("#mydiv").append('<br>GeoJSON data:<br>' + JSON.stringify(mydata));
};
//$("#mydiv").append('GeoJSON data: ' + JSON.stringify(mydata));
if(typeof mydata === 'undefined') {
console.log("undefined data")
} else {
console.log("not undefined")
}
$(document).ready(debugAjax());
Avoid defining several functions and try just using this:
$(document).ready(function(){
$.ajax("data/MegaCities.GeoJSON", {
dataType: "json",
success: function(response){
$("#mydiv").append('<br>GeoJSON data:<br>' + JSON.stringify(response));
}
});
});
Note that after we get response/data from ajax call, we proceed formatting as JSON.
You are using var mydata and it is not defined so it is showing correct message undefined when you are passing it as value.
You should probably modify your code like this.
$(document).ready(function(){
$.ajax({
url: "data/MegaCities.GeoJSON",
method: 'GET' ,
aysnc: false,
success: function(response){
$("#mydiv").append('GeoJSON data:' +response);
}
});
});

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