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

               function (data) {});
    }
});
2
  • 2
    You've to put that code in the callback of ajax call. because it;'s async in nature Commented Aug 18, 2015 at 11:08
  • possible duplicate: stackoverflow.com/questions/6685249/… Commented Aug 18, 2015 at 11:11

3 Answers 3

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

});
Sign up to request clarification or add additional context in comments.

2 Comments

Forcing async: false is bad practice and in some uses depricated
@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
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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.