Giles Taylor Giles Taylor - 3 months ago 18
Ajax Question

JavaScript/jQuery callback using Ajax

I'm having trouble with my functions running before Ajax requests (the first to a local JSON, the second to an online resource) have finished.

In this example I want

countTheMovies
to run at the end after my application has got all the information it needs and populated the divs. Instead it's running straight away.

I tried to delay it using an
if
condition, but with no joy. I've also tried with callbacks, but think I must be getting those wrong (I'm assuming callbacks are the answer). I'm aware of timed delays, but because in the actual project I'm sourcing 250+ movies (and because a timed delay seems like cheating) I thought I'd ask here instead.

Can anyone recommend JavaScript or jQuery code to fix this problem?

$(function(){
getMovieList();
});

function getMovieList() {
$.ajax({
url: "movielist.json",
type: "GET",
dataType: "JSON",
success: function(data) {
for (var i = 0; i < data.length; i++) {
var title = data[i].title.toLowerCase().split(" ").join("+");
var year = data[i].year;
i === data.length - 1
? getMovieInfo(title, year, true)
: getMovieInfo(title, year, false);
}
}
});
}

function getMovieInfo(title, year, isLast) {
$.ajax({
url: "https://www.omdbapi.com/?t=" + title + "&y=" + year + "&plot=short&r=json",
type: "GET",
crossDomain: true,
dataType: "JSON",
success: function(val) {
if (!val.Error) {
movie = title.replace(/[^a-z0-9\s]/gi, '');
$("#app").append(
// appending info to divs
);
}
}
});
if (isLast) countTheMovies();
};

function countTheMovies() {
$("#app").append("There are " + $(".movie").length + " movies.");
}


A plunker of my failings: https://plnkr.co/edit/0mhAUtEsaOUWhkZMJqma?p=preview

Answer

Just put your countTheMovies() logic inside of the success callback of the AJAX request in getMovieInfo if you want it to run on success.