How can I pass true or false outside of this Ajax function? I need to return false on something and I cannot do that within Ajax
var zip = $('#order-zip').val();
var zipvalidated;
$.ajax({
type: 'POST',
url: 'checkzip.php',
data: {post:zip},
dataType: 'json',
success: function(data) {
zipvalidated = true;
if (data.response !== "success"){
console.log(data);
console.log ("sorry, we are not delivering in your area right now");
zipvalidated = false;
}
}
});
console.log (zipvalidated);
if (zipvalidated == false) {
return false;
}else{
console.log ("pass!")
}
3
Answers
Ajax is by default async,
So your if statement runs before zipvalidated variable is updated.
Use async/await or try setting async: false on your ajax request.
You can force your request to be syncronous with async: false , but that’s not recommended because it will cause the browser to lock up while waiting for results.
You can use callback function instead
Just put the checking in your callback function