javascript - Can't get jQuery to execute code in the correct order -
i having ordering issues. have code following: on page load, loop through 3 tables , grab content server , populate table said content make table responsive
i having issues making work. can achieve fine through inspect element (calling functions) that's not user friendly. want know if there's way can choose ordering on function being executed. have far is:
$(document).ready(function() { if (datecounter == null){ //start calendar today's date var current = new date(); datechange(current, "", 0); //function 1 grab contents //make table responsive var switched = false; var updatetables = function() { if (($(window).width() < 992) && !switched ){ console.log("window width < 992px"); switched = true; $("table.responsive").each(function(i, element) { console.log("splitting table up"); splittable($(element)); }); return true; } else if (switched && ($(window).width() > 992)) { switched = false; $("table.responsive").each(function(i, element) { unsplittable($(element)); }); } }; function splittable(original){...} function unsplittable(original){...} } });
in theory, on page load, should populate table first, make table responsive, that's not case. seems rendering concurrently , therefore lots of missing/hidden content in table. don't know if ajax call in datechange function has preventing table displaying content correctly.
following code snippet of datechange function:
function datechange(dateinput, nguests, vname){ //format dates //for each table (3 tables) $(".title").each(function(index, element) { //prepare html grabbing content server //grab content server , pop table $.ajax({ url: "/grab_content.asp?boattype="+boatname+"&date="+dateinput+"&guests="+guests+"&boatname="+vname+"", datatype:"html", success: function(data){ table.html(data); } }); }); }
yes, ajax calls asynchronous. $.ajax
returns promise can use control sequence. first, return promise datechange
:
function datechange(dateinput, nguests, vname){ return $.ajax({ //... }); }
then when call it:
datechange(current, "", 0).then(function() { //make table responsive var switched = false; //.... }
that make sure ajax call completes before make table responsive.
if have multiple ajax calls, you'll have store promises in array , use $.when
:
var promises = []; $('.whatever').each(function() { var promise = $.ajax({ /*...*/ }); promises.push(promise); }); $.when.apply($, promises).done(function() { console.log('all done'); // work.... });
note have use function.prototype.apply
because $.when
treats array of promises single promise.
Comments
Post a Comment