How to use Jquery $.each() with ajax

196
January 28, 2018, at 5:41 PM

I'm trying to send SMS to recipients from a object.
Does Jquery each loop wait for ajax success before continue?

I'd like my script to send one SMS and append a success text to DOM before continue with next recipient. When the each loop is done, i'd like to have a success message.

var i = 1;
var count =  Object.keys( recipients ).length;
//LOOP threw recipients
$.each(recipients, function(nr, name){
    //SEND SMS
    $.ajax({
        url: 'php/sms_send.php',
        method: 'POST',
        data: {nr: nr, name: name, text: text},
        success: function(result){
            //ECHO STATUS
            $('<span>'+result+'</span><br>').appendTo('#recipients');
        },
        error: function(err){
            //console.log(err);
        }
    }); //AJAX
     //LAST ROW?
    if(count === i){
        //DISABLE BTN
        $('#send_sms_btn').removeClass('disabled');
        $('#send_sms_btn').text('Skicka');
        //ECHO STATUS
        $('<span class="text-success">Klar!</span><br>').appendTo('#recipients');
    }
    else{
        i++;
    }
}); //EACH

The count does not work correct, and i wonder if the each is waiting for the ajax or if it just runs?

How can i make this workflow better?

Answer 1

You don't need a messy count.

Just aggregate the jqXHR promises returned by $.ajax() and do whatever is necessary when they have all resolved.

// map recipients to promises
var promises = $.map(recipients, function(name, nr) {
    // return a jqXHR promise
    return $.ajax({
        'url': 'php/sms_send.php',
        'method': 'POST',
        'data': { 'nr': nr, 'name': name, 'text': text }
    }).then(function(result) {
        $('<span>' + result + '</span><br/>').appendTo('#recipients');
    });
});
// now aggregate the promises
$.when.apply($, promises).then(function() {
    // arrive here when all promises have resolved
    $('#send_sms_btn').removeClass('disabled').text('Skicka');
    $('<span class="text-success">Klar!</span><br>').appendTo('#recipients');
});
READ ALSO
Jquery nested grouping

Jquery nested grouping

I have a list of events, the system generates them individually

152
Getting Data Items from MySQL database using AJAX, PHP and JSON

Getting Data Items from MySQL database using AJAX, PHP and JSON

I'm stuck getting my AJAX/PHP to workI'd really appreciate it if someone can help me to spot the error(s) I'm making

163
Updating an array embedded object in MongoDB

Updating an array embedded object in MongoDB

please how do i update this embedded document within an array:`id : 5a6d780fe397d837fc3db3dd username : "lindabens" name : "Linda Bens" email : "zainab@gmailcom" password : "pass" cover : "mode

171