I have a function that goes and grabs some information from a database and performs some logic using PHP, making this process take anywhere between 5 and 10 seconds for each of the results in the database - sometimes the whole process takes like 5 minutes total.
The only way of me knowing when all the process is finished is by using jQuery deferred calls, since it all runs asynchronously, but sometimes the user might want to stop this process and start over again with different parameters.
I have searched for how to stop these calls but can't find anything, I read about $deferObj.reject() but it's not working for me, I get $deferObj.reject is not a function
Basically all I want to do is to start the process, and when I click a Stop button then the deferred calls to stop. Right now this is not happening and for me to get out of there or even refresh to start over, it takes a bit of time while the rest of the deferred calls finish.
Here's my code that starts up the deferred calls:
var getBooks = function( title ) {
return $.ajax({
url: 'ajax-handler.php',
data: {action: 'get_books', title: title, params: $( '#params' ).val()},
method: 'POST',
dataType: 'json',
success: function( results ) {
if ( results.error ) {
console.log( 'Got an error processing ' + title );
}
}
});
}
var books = new Array( 'Book 1', 'Book 2', 'Book 3', 'Book4' );
var defBooks = new Array();
for ( var i = 0; i < books.length; i++ ) {
defBooks.push( getBooks( books[ i ] ) );
}
deferBooks = $.when.apply( $, defBooks );
deferBooks.done( function() {
alert( 'Process finished correctly' );
}).fail( function () {
alert( 'Process failed' );
});
This code works just fine, I only get a Process failed message when I either have network issues or just something wrong in my PHP code, so everything needed to be done in the backend is being done.
Now, I also have a Stop Process button, that's supposed to stop all executions and allow me to start over, here's the code for that button's click event:
$( document ).on( 'click', '#stop-button', function() {
deferBooks.reject(); // this one gives me the **deferBooks.reject is not a function** error message in the console
});
Please note that the deferBooks variable I have tried declaring it at the very top of my scripts file so that it's available in all functions, that's why I don't get a deferBooks is undefined message.
I'm out of ideas, this is my first time using deferred calls, so I might be missing something obvious...
Anyone who can give me some guidance on this?
Thanks