JQuery, when each one is completed, the trigger function

How to run a function, like redirecting to a new page when .each is executing, iterating over my elements? this is my current code:

$('#tabCurrentFriends > .dragFriend').each(function(){ var friendId = $(this).data('rowid'); $.ajax({ type: "POST", url: "../../page/newtab.php", data: "action=new&tabname=" + tabname + "&bid=" + brugerid + "&fid=" + friendid, complete: function(data){ } }); }); 
+4
source share
2 answers

You can use $.when() / $.then() to redirect your users after all AJAX requests have completed:

 //create array to hold deferred objects var XHRs = []; $('#tabCurrentFriends > .dragFriend').each(function(){ var friendId = $(this).data('rowid'); //push a deferred object onto the `XHRs` array XHRs.push($.ajax({ type: "POST", url: "../../page/newtab.php", data: "action=new&tabname=" + tabname + "&bid=" + brugerid + "&fid=" + friendid, complete: function(data){ } })); }); //run a function when all deferred objects resolve $.when(XHRs).then(function (){ window.location = 'http://stackoverflow.com/'; }); 

Edit - use when with an array, apply should be used:

 $.when.apply(null, XHRs).then(function () { window.location = 'http://stackoverflow.com/'; }); 

jQuery AJAX queries create deferrable objects that resolve when fully run. This code stores those deferrable objects in the array and when all of them allow the execution of the function inside .then() .

Docs:

+12
source

AJAX happens asynchronously, so you need to try something like this:

 var total = $('#tabCurrentFriends > .dragFriend').length; var completed = 0; $('#tabCurrentFriends > .dragFriend').each(function(){ var friendId = $(this).data('rowid'); $.ajax({ type: "POST", url: "../../page/newtab.php", data: "action=new&tabname=" + tabname + "&bid=" + brugerid + "&fid=" + friendid, complete: function(data){ completed++; if (completed == total) { // All have been loaded. } } }); }); 
+5
source

Source: https://habr.com/ru/post/1385692/


All Articles