0
$.each(emails, function(index, value) 
{
    $.post('ajax/send_email.php', { email: value, ... }, function(data)
    {
        $('#emails_sent').text('Sent ' + (index + 1) + '/' + num_emails);
    }); 
});

In

$(function()
{
    $('#cancel').on('click', function(e) 
    { 
        hidePopupWindow();
    });
});

While $.each is running none of the buttons such as cancel work — they can't be selected or pressed.

fedosov
  • 1,989
  • 15
  • 26
Luke Wenke
  • 1,149
  • 2
  • 23
  • 43
  • Possible duplicate of http://stackoverflow.com/questions/6571208/cancelling-the-current-ajax-request-via-a-button-click-event – krishwader Jul 04 '13 at 03:44
  • It doesn't matter if the current ajax request isn't cancelled since it lasts for less than a second... I want to stop the future requests and the buttons should be able to be focused on and clicked. – Luke Wenke Jul 04 '13 at 04:04

1 Answers1

1

You can modify your program to use maintain an array of currently existing xhr requests, then at cancel you can abort the XHR. See the code below:

var globalAbort = false,
xhrPool = [];
$.each(emails, function(index, value) {
    if (!globalAbort) {
        $.ajax("ajax/send_email.php", { 
            beforeSend: function(xhr){
                xhrPool.push(xhr);
            },
            email: value,
            success: function(data, status, xhr){
                var index = xhrPool.indexOf(xhr);
                if (index > -1) {
                    xhrPool.splice(index, 1);
                }
                $('#emails_sent').text('Sent ' + (index + 1) + '/' + num_emails);
            }
        });
    }
});
$('#cancel').on('click', function(e) { 
    var xhrLen = xhrPool.length;
    for (var i = 0; i < xhrLen; i++) {
        xhrPool[i].abort();
    }
    xhrPool.length = 0;
    hidePopupWindow();
});
Gautam Chadha
  • 306
  • 1
  • 6
  • The buttons still don't respond or show focus when pressing tab. Also the num sent doesn't seem to be updating past the first index - I fixed that but changing your "index" to "i". If I refresh the page or go to a different page on the same domain the ajax calls keep on coming. I'm using firebug for firefox. – Luke Wenke Jul 04 '13 at 05:44
  • BTW I'm using jQuery.ajaxSetup({async:false});.... at the end of it I've got an alert message. If I don't use async:false it shows the alert message straight away. If I don't use async:false then it doesn't keep the queue of ajax requests when I refresh the page. – Luke Wenke Jul 04 '13 at 05:45
  • It works if I stop setting jQuery.ajaxSetup({async:false});... I initially did that because there were hundreds of ajax calls at once and it told the user that it was too busy and they needed to confirm that they wanted to continue... but now I've put the emails in chunks using php's array_chunk to do 10 at a time. So now the buttons can be pressed and the cancel button aborts things. – Luke Wenke Jul 04 '13 at 06:13