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