the weirdest thing happened to me just now. In the second ajax call, the data[i]['imdb'] returns the value of the key 'imdb' from a json object. however, i found out that, at the bottem of this code snippet, the data[i] is undefined.
function fillallmovies() {
$.ajax({
url: "resources/movies",
dataType: "json",
}).fail(function (jqXHR, textstatus) {
alert(textstatus);
}).done(function (data) {
console.log(data);
for (var i = 0; i < data.length; i++) {
$.ajax({
url: 'http://www.omdbapi.com/?i=' + data[i]['imdb'] + '&t=',
}).fail(function(jqXHR, textStatus) {
alert(jqXHR.responseText);
}).done(function (ajaxdata) {
var json = JSON.parse(ajaxdata);
var image = (json['Poster']);
var elem = $('#moviecontainer');
var col = $('<div/>', {'class': 'col-sm-6 col-md-4'});
var thumbnail = $('<div/>', {'class': 'thumbnail' });
var img = $('<img/>' , {'src' : image , 'class' : "showimage"});
var caption = $('<div/>' , {'class' : 'caption'});
console.log(data[i]['imdb']);
var header = $('<h3/>').text(data[i]['title']);
my page can load the second ajax call using data[i]['imdb'], and it returns valid json. However the console.log(data[i]['imdb']) at the second to last line throws a Uncaught TypeError: Cannot read property 'imdb' of undefined
.
Why is data suddenly undefined?
It has infact nothing to do with loops and ajax. Data is undefined because the first ajax call has already been finished and cleaned up when the second call callbacks to .done(). Hence when i try to call the data from the first ajax call, it is undefined.