Ash
Ash

Reputation: 225

jQuery access variable outside each loop

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: '[email protected]',
            subject: 'New x x x',
            message: 'We x x x'
        },

               function (data) {});
    }
});

Upvotes: 0

Views: 262

Answers (3)

jimmy jansen
jimmy jansen

Reputation: 647

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

Upvotes: 0

DKSan
DKSan

Reputation: 4197

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.

Upvotes: 0

mohamedrias
mohamedrias

Reputation: 18566

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;
    }

});

Upvotes: 1

Related Questions