0

I need to access a var "cont" after each loop has run. I need to run an email if cont = true which is set after an ajax call in each loop. I've read that each loop is synchronous but when i console log var cont after each loop, i get false even though it is set as true.

$(".check").click(function (event) {
    var cont = false;
    event.preventDefault();
    $("form.form").each(function (index) {
        var $this = $(this);
        var name = $this.find('input.name').val();
        var company = $this.find('input.comp_name').val();
        var jtitle = $this.find('input.job_title').val();
        var link = $this.find('input.link').val();
        var email = $('input.email').val();

        if ((name === "") || (company === "") || (jtitle === "")) {
            $this.addClass("NotFilled");
        } else {
            var url = $this.attr('action');
            // fetch the data for the form
            var data = $this.serializeArray();
            $.ajax({
                url: url,
                data: data,
                type: "post",
                success: function (result) {
                    if (result === "success") {
                        cont = true;
                        $this.removeClass("NotFilled").addClass("filled");
                        //console.log(cont)  I Get True here
                    } else {
                        cont = false;
                        $this.removeClass("filled").addClass("NotFilled");
                    }
                    return cont;
                }

            });
        }
    });
    //console.log(cont)  I Get false here
    if (cont === "true") {
        $.post("<?php bloginfo('template_url'); ?>/x/x.php", {
            emailTo: email,
            emailFrom: 'x@x.co.uk',
            subject: 'New x x x',
            message: 'We x x x'
        },

               function (data) {});
    }
});
rrk
  • 15,677
  • 4
  • 29
  • 45
Ash
  • 225
  • 1
  • 5
  • 16

3 Answers3

1

The code inside your each method is ajax and it's async in nature.

So the statement

if(cont === "true"){

Will be executed even before the ajax calls succeeds/fails.

So you must either convert the ajax to be sync by setting the async flag or put the if condition inside the callback.

Example synchronous ajax call:

 $.ajax({
    url: url,
    data: data,
    async: false

    type: "post",
    success: function (result) {
        if (result === "success") {
            cont = true;
            $this.removeClass("NotFilled").addClass("filled");
            //console.log(cont)  I Get True here
        } else {
            cont = false;
            $this.removeClass("filled").addClass("NotFilled");
        }
        return cont;
    }

});
mohamedrias
  • 18,326
  • 2
  • 38
  • 47
  • Forcing async: false is bad practice and in some uses depricated – jimmy jansen Aug 18 '15 at 11:19
  • @jimmyjansen Ya, it's not recommended. But i'm just giving suggestions to make current code to work. The much better approach would be to use a promise and handle all the ajax requests to return a promise and when the promises resolves, trigger the if condition – mohamedrias Aug 18 '15 at 12:34
0

Since your call is asynchronous, the execution of the code will continue directly after the ajax call.

You can set $.ajaxSetup({async: false}); to have your code wait for the execution of the ajax call and set $.ajaxSetup({async: true}); after the execution.

DKSan
  • 4,187
  • 3
  • 25
  • 35
0

like @mohamedrias said: javascript is async from its very core. This means that your if statement is executed before the ajax call has returned a success or fail

consider the following code:

console.log('First');
jQuery.get('page.html', function(data) {
  console.log("Second");
});
console.log('Third');

In this snippet your console will log: First, Third, Second.

Now if we were to make this to run async:

console.log('First');
getPage("page.html, function(){
  console.log('Third');          
}


var getPage(url, callback) {
  jQuery.get(url, function(data) {
    console.log("Second ");
  }
  callback();
}

Now it logs: First, Second, Third

There are a lot of resources about this on the internet, the one I used to understand this is: this one

jimmy jansen
  • 647
  • 4
  • 12