0

I have each loop and after i have condition: if (flag)

The problem is that jquery runs the condition before the loop ends ( in the console i can see "console.log(flag);" before "console.log(data);" )

how can i run it only when the loop ends?

var flag = true;
$('.fileLink').each(function() 
{

        url = this.href;
        var fileName = $(this).attr("data-fileName");
        formData = "email= " + email + "&url=" + url + "&fileName=" + fileName;     

        $.ajax({
            type        : 'POST', 
            url         : 'ajax/emailFiles.php', 
            data        : formData, 
            dataType    : 'json', 
            code        : true
        })

            .done(function(data) {

                console.log(data); 

                if ( !data.success) 
                    flag = false;   
            });

});

console.log(flag); 
if (flag)
    $("#emailDocks_form-msg").html('<div class="alert alert-success">SUCCESS</div>');
else
    $("#emailDocks_form-msg").html('<div class="alert alert-danger">ERROR</div>');
Jaydeep
  • 1,686
  • 1
  • 16
  • 29
Roi
  • 109
  • 3
  • 11
  • 2
    In summary: because `a` in `ajax` stands for *asynchronous* – freedomn-m Jun 24 '19 at 08:24
  • @freedomn-m - is there anything i can do in order to finish the loop before jquery run my condition? – Roi Jun 24 '19 at 08:45
  • Depends, if you want to blast them all off at the same time and potentially overload your server (as you do now), then add each `$.ajax` call to an array and use `$.when(array).then(..check flag/alert ..)` https://stackoverflow.com/a/21284591/2181514 if you want to queue the ajax calls then you'll need to manage them, eg: https://stackoverflow.com/q/4785724/2181514 – freedomn-m Jun 24 '19 at 09:01

0 Answers0