how do start a function like redirecting to a new page when .each is done looping 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){
}
});
});
each(), which is used to iterate, exclusively, over a jQuery object. The $. each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.
To call a jQuery function after a certain delay, use the siteTimeout() method.
The .each() method is designed to make DOM looping constructs concise and less error-prone. When called it iterates over the DOM elements that are part of the jQuery object. Each time the callback runs, it is passed the current loop iteration, beginning from 0.
var flagu6=0; if( flagu1==0 && flagu2==0 && flagu3==0 && flagu4==0 && flagu6==0 ) return true; else return false; } function clearBox(type) { // Your implementation here } // Event handler $submitButton. on('click', handleSubmit); }); Now, clicking the button will go to handleSubmit function, which employs your code.
You can use $.when()
/$.then()
to redirect your users after all the AJAX requests are done:
//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 - to use when
with an array, apply
must be used:
$.when.apply(null, XHRs).then(function () {
window.location = 'http://stackoverflow.com/';
});
jQuery AJAX requests create deffered objects that resolve when their complete function fires. This code stores those deffered objects in an array and when they all resolved the function within .then()
is run.
Docs:
$.when()
: http://api.jquery.com/jquery.when
$.then()
: http://api.jquery.com/deferred.then/
AJAX happens asynchronously, so you'll have 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.
}
}
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With