Giles Taylor Giles Taylor - 2 months ago 5x
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

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
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() {
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) {
url: "" + 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, '');
// appending info to divs
if (isLast) countTheMovies();

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

A plunker of my failings:


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