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