skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. 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)
    
    Login or Signup to reply.
  3. 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!")
                }
    
            }
        }
    });
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search