how to get result of getjson promise inside $.when function? - javascript

using the following code i try to get data of 2 getjson calls into array only when both getjson called completed. The code give me this error:
resultFromUrl1.feed is undefined
var entry1 = resultFromUr11.feed.entry;
i looked at f12 i saw both getjson executed successfully but no data get put into the array! how to fix this error ? furthermor should i use $.when(url1Promise, url2Promise).then or $.when(url1Promise, url2Promise).done ?
<javascript>
var files = new Array();
function pushtoArray() {
//first getjson call
var url1 = "https://spreadsheets.google.com/feeds/list/xxxxx/xxxxx/public/values?alt=json";
var url1Promise = $.getJSON(url1, function (data) {
console.log("url1 success");
});//end of ajax call
//second getjson call
var url2 = "https://spreadsheets.google.com/feeds/list/xxxxx/xxxxx/public/values?alt=json";
var url2Promise = $.getJSON(url2, function (data) {
console.log("url2 success");
});//end of function
$.when(url1Promise, url2Promise).then(function (resultFromUrl1, resultFromUrl2) {
var entry1 = resultFromUrl1.feed.entry;
var entry2 = resultFromUrl2.feed.entry;
var entry = entry1.concat(entry2);
$(entry).each(function () {
// Column names are name, age, etc.
count++;
files.push({ url: this.gsx$url.$t, filename: this.gsx$name.$t });
alert(files.length);
print_r(files);
console.log(files);
});
});
}//end of function
</javascript>
<body onload="pushtoArray()">

jQuery ajax functions are a bit of a pain to use with $.when(). What is is in resultFromURL1 is actually an array of three values like this: [data, textStatus, jqXHR].
So, you need to change to:
var entry1 = resultFromUrl1[0].feed.entry;
var entry2 = resultFromUrl2[0].feed.entry;
In addition, you should add an error handler to your $.when().then() construct so you can see if any errors occurred in your getJSON() calls.

I tried your example using this url: "https://spreadsheets.google.com/feeds/list/o13394135408524254648.240766968415752635/od6/public/values?alt=json"
It works fine..
You are receiving data. You can access the data by writing
resultFromUrl1[0].feed.entry
resultFromUrl2[0].feed.entry;

Related

Why does the script work line by line, but does not work as a whole?

If I run this script all by Chrome Console - I get error
Uncaught TypeError: Cannot read property 'playlist' of undefined
var owner = "yamusic-trending"
var kind = "1000"
var url = `https://music.yandex.ru/handlers/playlist.jsx?owner=${owner}&kinds=${kind}&light=false`
json = $.getJSON(url)
var tracks = json.responseJSON["playlist"]['tracks']
By if line by line
json = $.getJSON(url)
And then
var tracks = json.responseJSON["playlist"]['tracks']
Error is not. Why?
As $.getJSON is an async function, you must handle it once it's done, here is an example using a callback:
$.getJSON(url, json => {
var tracks = json.responseJSON["playlist"]['tracks']
// do something with tracks here...
})
Read more about $.getJSON here , and read more about how asynchronous javascript works here
$.getJSON is aynchronous call and you need to wait until it get completed. If any of the operation dependes on the result return by this call then it should be handled in callback function.
see below code
ES5
$.getJSON(url, function(data){
var tracks = data.responseJSON["playlist"]['tracks']
});
ES6
$.getJSON(url, json => {
var tracks = json.responseJSON["playlist"]['tracks']
});
getJSON API Documentation

Use the data from 1st JSON and convert it to a variable and use that variable to call a 2nd JSON

I am new here but I have a problem and need your help, so in my code I called a JSON file.
var data = {};
var spectator;
var tmp = [];
var IDcatcher =[];
var summonerID = [];
$.getJSON(getUrl, function(data) {
tmp = data;
$.each(tmp, function(key){
for (IDcatcher in tmp) {}
});
summonerID = tmp[IDcatcher].id;
});
so this gives me the ID from the JSON which is stored in summonerID variable now I want to use this variable to complete the URL to get the 2nd JSON so.
var spectatorUrl = "link" + summonerID;
Now get the 2nd JSON
var Charcatcher =[];
var CharID = [];
$.getJSON(spectatorUrl, function(data) {
tmp = data;
$.each(tmp, function(key){
for (Charcatcher in tmp) {}
});
CharID = tmp[Charcatcher].id;
});
My problem is the 2nd JSON doesn't run, it doesn't get anything and returns nothing (obviously).
Help?
I can't run 2 JSONs at different times? If so how can I do it or change it?
As I mentioned, due to the asynchronous nature of JavaScript, if you have an AJAX request with a callback and some code following the request, JS will fire off the AJAX request and will continue with the rest of the code. It won't wait for the result of the AJAX request to return.
Here's a simple demo -
function first() {
setTimeout(() => {
console.log("1");
}, 2000);
console.log("2");
};
first();
Look at the order of the console.log statements in the code, and then check the actual order in the console.
To solve your original problem, you can nest a $.getJSON() inside the first one, this will ensure that summonerID is available when you fire off the second AJAX request.
$.getJSON(getUrl, function(data) {
tmp = data;
$.each(tmp, function(key){
for (IDcatcher in tmp) {}
});
summonerID = tmp[IDcatcher].id;
// second AJAX request
var spectatorUrl = "link" + summonerID;
$.getJSON(spectatorUrl, function(data) {
// logic
});
});

how to pass object array to another function ONLY when all getjson calls completed?

i have to make a few getjson calls to get some data from google spreadsheet and store the data i need to an array and filter the array and display the data. My current code some time for large amount of data passes array before my first getjson finishes so i end up with incomplete data in my array!
Is there a way that my last getjson sends the array to another function only when all previous getjson calls finished (including itself) before passing the array to another function?
<script>
var files = new Array();
function pushtoArray(){
//first getjson call
var url1 = "https://spreadsheets.google.com/feeds/list/xxxxx/xxxxx/public/values?alt=json";
$.getJSON(url1, function(data) {
var entry = data.feed.entry;
$(entry).each(function(){
// Column names are name, age, etc.
count++;
files.push({ url: this.gsx$url.$t, filename: this.gsx$name.$t });
});
alert(files.length);
print_r(files);
console.log(files);
});//end of ajax call
//second getjson call
var url2 = "https://spreadsheets.google.com/feeds/list/xxxxx/xxxxx/public/values?alt=json";
$.getJSON(url2, function(data) {
var entry = data.feed.entry;
$(entry).each(function(){
// Column names are name, age, etc.
count++;
files.push({ url: this.gsx$url.$t, filename: this.gsx$name.$t });
});
alert(files.length);
passArray(files);
console.log(files);
});//end of ajax call
};//end of function
function passArray(files){
alert(files.length);
console.log(files);
// do some data filtering from array passed
</javascript>
<body onload="pushtoArray()">
edit: i changed
var entry1 = resultFromUrl1.feed.entry;
var entry2 = resultFromUrl2.feed.entry;
to
var entry1 = resultFromUrl1[0].feed.entry;
var entry2 = resultFromUrl2[0].feed.entry;
and it fixed the error!
use Promises.
var promiseA = $.getJSON(urla..);
var promiseB = $.getJSON(urlb..);
$.when(promiseA, promiseB).then(function(resultA,resultB){
//do whatever you want with results.
});
EDIT:Here's your code edited, maybe an issue with var entry = ... if so then just look at entry1 and entry2 in debug:
var files = new Array();
function pushtoArray() {
//first getjson call
var url1 = "https://spreadsheets.google.com/feeds/list/xxxxx/xxxxx/public/values?alt=json";
var url1Promise = $.getJSON(url1, function (data) {
console.log("url1 success");
});//end of ajax call
//second getjson call
var url2 = "https://spreadsheets.google.com/feeds/list/xxxxx/xxxxx/public/values?alt=json";
var url2Promise = $.getJSON(url2, function (data) {
console.log("url2 success");
});//end of function
$.when(url1Promise, url2Promise).then(function (resultFromUrl1, resultFromUrl2) {
var entry1 = resultFromUrl1.feed.entry;
var entry2 = resultFromUrl2.feed.entry;
var entry = entry1.concat(entry2);
$(entry).each(function () {
// Column names are name, age, etc.
count++;
files.push({ url: this.gsx$url.$t, filename: this.gsx$name.$t });
alert(files.length);
print_r(files);
console.log(files);
});
});

Why my multi javascript array can no pass the data throw ajax?

var model = new Array();
function saveItem(id){
var title = $("#inputTitle_"+id).val();
var url = $("#inputPicurl_"+id).val();
var content = $("#content-editor-"+id).html();
model[id] = new Array();
model[id]['inputTitle'] = $("#inputTitle_"+id).val();
model[id]['inputPicurl'] = $("#inputPicurl_"+id).val();
model[id]['author'] = $("#author_"+id).val();
model[id]['content'] = $("#content-editor-"+id).html();
$("#title_"+id).text(model[id]['inputTitle']);
console.log(model);
}
$("#submit_form").click(function(){
$.ajax({
url:'materials/addpics',
type:'post',
dataType:'json',
data:model,
traditional:'true',
success:function(data){
console.log(data)
}
});
});
when the saveItem() run,the console log is array[],but the data named model in ajax is NULL?
"when the saveItem() run, ..." saveItem is never run. You've defined the function, but you haven't called it anywhere in your code. You probably meant it to be the success handler, instead of the handler you've got that just logs data. (Except that the argument to saveItem doesn't seem to match the argument supplied to the handler.)

How to use YAHOO.util.Connect.asyncRequest and return results?

I'm using YAHOO.util.Connect.asyncRequest to get data from database, here is the code :
function getCountArticle(contentCurValue) {
var handleSuccess = function (res) {
var countPubmed = YAHOO.lang.JSON.parse(res.responseText);
var contentCountPubmed = countPubmed.totalArticleRecords;
alert(contentCountPubmed); //return 15 for example
};
var handleFailure = function () {
alert("Error connecting data : Bad pubmed query");
};
var callback =
{
success:handleSuccess,
failure:handleFailure,
timeout: 5000
};
var sURL = 'qct-list-article.html?term=' + contentCurValue + '&retstart=0' + '&retmax=1';
var request = YAHOO.util.Connect.asyncRequest('GET',sURL,callback);
}
I would like this function return : "contentCurValue" (eg:15), but when I try to use this code I get "undefined" :
var test = getCountArticle();
alert(test); // return undefined, should return 15
My error is probably due to asynchronous query, but how can I force "var test = getCountArticle();" to wait for results ?
Since the call is by nature asynchronous, rather than try to wait for the response, you would be better off specifying a callback function to execute with the data. You could modify your method like this:
function getCountArticle(contentCurValue, callback) {
var handleSuccess = function (res) {
var countPubmed = YAHOO.lang.JSON.parse(res.responseText);
var contentCountPubmed = countPubmed.totalArticleRecords;
callback(contentCountPubmed); //return 15 for example
};
// ...
}
then your calling code would be:
getCountArticle("contentCurValue", function(test) {
alert(test);
});
Any further execution using the value returned from your AJAX query would proceed inside of your callback method.
This SO post is essentially the same problem, but not YUI specific: Getting undefined in javascript when calling ajax

Categories

Resources