Currently fetching the first video from a search on YouTube using the code below, but when docready is called, the ids are not set. The code does not wait for the ajax results to be returned, instead it continues and returns nothing.
I’ve tried the async:false with the ajax thinking it might make it ‘wait’ but still nothing is returned. How would I fix this so all the ids will be set?
$(document).ready(function () {
docready();
});
function docready() {
var id1 = grabid("cat");
var id2 = grabid("dog");
var id3 = grabid("goldfish");
alert(id1);
}
function grabid(keyword) {
var url = 'http://gdata.youtube.com/feeds/api/videos?q=' + encodeURIComponent(keyword) + '&format=5&max-results=1&v=2&alt=jsonc';
$.ajax({
async: false,
type: "GET",
url: url,
dataType: "jsonp",
success: function (responseData, textStatus, XMLHttpRequest) {
if (responseData.data.items) {
var videos = responseData.data.items;
videoid = videos[0].id;
alert(videoid);
return videoid;
}
}
});
}
UPDATE: I’ve just changed the code above a bit to make my problem a bit clearer. When the code is run it alert’s the real ‘videoid’ 3 times as expected. But when it gets to alert(id1) it returns undefined – so the ‘return videoid’ is ignored and not passing it back to the variable.
UPDATE 2 STILL UNSOLVED
Firstly you have problem with your ajax call try this..
EDIT:
Updated code to get return from ajax call :
Remove all your onload or document ready functions,this should work.
EDIT :
The only thing you can do is doing async:false, which will wait for the ajax call to finish and return a value… but CROSS DOMAIN calls are not synchronous so I can say you are out of luck.. You need to re think on the logic of ajax calls.
Also As of jQuery 1.8, the use of async: false is deprecated.