jquery - How do you use .when().then() to trigger a function when using deffered objects in the .when()? -
i have page in have variable number of ajax calls create triggered on mutual event. ajax calls update related fields in sql database. 1 time calls complete, want refresh page reflects changes made.
i used next question/answer on here far.. jquery when each completede trigger function
here code far:
var team_update = function(e) { var $items = $('.sortable-items'); var xhrs = []; $items.each(function(){ var team_id = $( ).attr("id"); var info = { tid: team_id, users: $('#' + team_id).sortable('toarray') }; xhrs.push( $.ajax({ type: "post", url: "update.php", data: data, complete: function(data){ } }) ); }); $.when(xhrs).then(function(){ console.log('refreshing screen'); $('#content-wrapper').load( 'index.php' ); }); } what expecting happen, $('#content-wrapper').load( 'index.php' ); fire, 1 time ajax() requests had completed. appears happening though, callback firing 1 time requests have been sent, not after have completed, , page update still has 'old' info on it.
the graphic below shows initial page load @ top, can ignored. next 4 entries show issue. there 3 post requests 3 ajax calls update db, , final page refresh. page refresh fires after 3 ajax calls have been sent, doesn't wait lastly ajax phone call finish before fires. consequence, gets old info completes before previous ajac phone call has finished updating database.
what doing wrong here?
i applied similar.
when() expects deferred object or list of deferred objects, if want utilize array, need utilize apply().
replace
$.when(xhrs) with
$.when.apply(null, xhrs) if not work, might need wrap ajax phone call in function:
function sendajax(data){ homecoming $.ajax({options in ajax call}); } and force them xhrs such:
xhrs.push(sendajax(data)); the next how implemented in code, can adapt if needed:
//we want notify how many memberships have been made after they're made. since they're async, we'll need utilize promises //however, because repeat same ajax phone call different parameters, need force them array , apply() them. checkedboxes.each(function () { createarray.push(createmembershipsajax(this)); }); //we did work before start creating them, show progress; add1toprogress(); $.when.apply(null, createarray).done(function () { //this function start 1 time ajax calls have been successfull. divcreated.append(membershipcount + " memberships created:"); membershipscreated = true; window.close(); }); ... createmembershipsajax(element){ //process element, create info it; homecoming $.ajax({option}); } and yes, comments in code , not added clarification on page.
jquery ajax jquery-deferred
No comments:
Post a Comment