I’m trying to dynamically add titles to a number of images using values obtained from a JSON call.
This is what I have so far
$(".watch_view img").each(function() {
$.ajax({
url: 'http://gdata.youtube.com/feeds/api/videos/T2aMBeeM4yw?v=2&alt=jsonc',
dataType: 'json',
success: function(json) {
song_title = json.data.title;// song title is retrieved without issue
}
});
alert(song_title); //this to be removed
//the title attr below is only added when the above alert is in place
$(this).attr('title', song_title);
$(this).attr('alt', "This works everytime");
});
Now the above works but only when I “stop” the process by adding in the unwanted alert – I can only guess that the code is executing before it has retrieved the data from the JSON call (?) and the alert enables it to catch up.
I imagine I need another function that executes after the JSON call or for the code to go into the ‘success’ function but I’m not sure how to keep hold of the ‘this’ element if that is the case.
Help and advice greatly appreciated.
Thanks
Chris
Keep in mind that AJAX stands for Asynchronous JavaScript. It means the browser will not be unresponsive while communication with server is in progress.
When you call
$.ajax(...)function, the script continue after it, not waiting for the response (you can configure it to wait, but then it would be a synchronous call).When the server returns with success, you should respond to that event, thus, your response handling code must be in
successfunction body:In your old code, the alert was reached before the server returned. When you placed a breakpoint, it worked because there was enough time for the server to return an answer while you were doing your human-time handling 🙂
Update
Additionally, you should know that
thisinside thesuccesscallback refers to the returned data, overriding the expectedthisfor theeach(which would be the iterated element). You have to actually declare the params for theeachcall, so that you can refer back to them inside the success call.