JavaScript/jQuery callback using Ajax -


i'm having trouble functions running before ajax requests (the first local json, second online resource) have finished.

in example want countthemovies run @ end after application has got information needs , populated divs. instead it's running straight away.

i tried delay using if condition, no joy. i've tried callbacks, think must getting wrong (i'm assuming callbacks answer). i'm aware of timed delays, because in actual project i'm sourcing 250+ movies (and because timed delay seems cheating) thought i'd ask here instead.

can recommend javascript or jquery code fix problem?

$(function(){   getmovielist(); });  function getmovielist() {   $.ajax({     url: "movielist.json",     type: "get",     datatype: "json",     success: function(data) {       (var = 0; < data.length; i++) {         var title = data[i].title.tolowercase().split(" ").join("+");         var year = data[i].year;         === 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 divs         );       }     }   });   if (islast) countthemovies(); };  function countthemovies() {   $("#app").append("there " + $(".movie").length + " movies."); } 

a plunker of failings: https://plnkr.co/edit/0mhautesaouwhkzmjqma?p=preview

just put countthemovies() logic inside of success callback of ajax request in getmovieinfo if want run on success.


Comments