0

I have an $.each() loop, looping through some selected checkboxes and calling an ajax call for each of the checkboxes. Obviously, $.each() doesn't wait on the ajax. I could put ajax:false on the ajax call, but due to deprecation warnings, I'd rather not.

Therefore, I'm trying to use $.Deferred(), but the each iteration doesn't appear to be waiting on it either.

Here's the code:

.each($checkboxes, function(key, checkbox) {
  $def = $.Deferred();
  $checkbox = $(checkbox);

  $.ajax({
    'url': 'ajax/myajaxcall.php',
    'data': {
       id: $checkbox.data('id')
     }
  }).complete(function() {
    console.log('done');
    $def.resolve('done');
  });

  return $def.promise();
});

ACTUAL SOLUTION

I'm fully aware of how to use ajax, however the above code had gone through a number of refactors and trials of different ways to do things to try to get the result I wanted.

What i've decided to do is drop the $.each() and manually interate through the checkboxes by calling a function which, when completed recalls itself with an incremented key for the checkboxes.

This solution 100% ensures that the ajax calls are being ran one-by-one.

var $checkboxes = $('input[name="mycheckboxes"]:checked'),
        checkboxKey = 0,
        checkboxLength = $checkboxes.length;


    function callAjax(key) {
        console.log(key);
        $checkbox = $($checkboxes[key]);
        console.log('call ajax');
        console.log($checkbox);

        $.ajax({
            'url': 'ajax/myajaxcall.php',
            'data': {
                'id': $checkbox.data('id')

            }
        }).complete(function() {
            console.log('done');
            if(key < checkboxLength-1) {
                key += 1;
                createInvoice(key);
            }
            else {
                console.log('complete');

            }
        });


    }

    if(checkboxLength > 0) {
        callAjax(checkboxKey);
    }
David
  • 16,246
  • 34
  • 103
  • 162
  • This feels like an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) to me: why can't your endpoint accept an array of checkbox IDs? In this case, you don't have to make a call for *every* single checkbox, but instead collect them and make a single call instead. Also, do you mean using `$.each()`? – Terry May 14 '18 at 11:30
  • Because `each()` isn't an async aware method, ie it isnt going to use defered, thenable, or promises. Nor does returning anything do anything. With the exeception of returning `false` which breaks out of the `each()` method early – Patrick Evans May 14 '18 at 11:30
  • Returning from `each()`? Do you even use it? Please post a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). – 31piy May 14 '18 at 11:34
  • Why do you have to start one request per checkbox? Get all the ids from the selected checkboxes and send them all in one request. – Andreas May 14 '18 at 11:41
  • The real problem is that you are not familiar with working with async code (no worries, everybody has to start somewhere!) Check the duplicate to see how to *"return"* a response from an asynchronous call. – Adam Jenkins May 14 '18 at 11:47
  • @Terry the ajax call is quite intensive, and thus best to only handle 1 at a time. Sending them all at the same time would likely timeout or cause major server strain. Furthermore, I'd like to create a realtime Ajax queue for the user to see a progress of the upload. I understand each() doesn't handle a return, it was a failed shot in the dark to try to get it to work. – David May 14 '18 at 11:50
  • How that is a duplicate, I will never know. I've decided to drop the $.each() and manually iterate through the checkboxes and call a function, when on completion, runs itself again with an incremental key for the checkboxes. – David May 14 '18 at 12:17

0 Answers0