0

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!")
}
jac
  • 13
  • 3
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – freedomn-m Sep 30 '20 at 08:17

3 Answers3

1

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

const zip = $('#order-zip').val()
var zipvalidated = true

function getZip(zip,callback) {
    $.ajax({
        type: 'POST',
        url: 'checkzip.php',
        data: {post:zip},
        dataType: 'json',
        success: function(data) {
            callback(data)
        }
    })
}

getZip(zip,function(data) {

    if (data.response !== "success"){
        console.log(data);
        console.log ("sorry, we are not delivering in your area right now");
        zipvalidated = false;
    }
})

console.log (zipvalidated)
Jerson
  • 1,700
  • 2
  • 10
  • 14
0

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.

  • not good idea, you can also use callback function instead – Jerson Sep 30 '20 at 03:55
  • Please don't recommend `async:false` - it's currently deprecated in chrome (and other browsers no doubt, didn't bother checking) and will be removed in the future. – freedomn-m Sep 30 '20 at 08:18
0

Just put the checking in your callback function

$.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!")
            }

        }
    }
});

York Chen
  • 744
  • 4
  • 9