tmartin314
tmartin314

Reputation: 4171

jQuery AJAX callback

I'm having a difficult time trying to get this javascript function to return false inside of a .post() function.

Is this even possible? or is there another way to do a simple ajax check to validate the voucher code is in the database.

function check_options(){       
        var voucher_code = $('#voucher_code').val();
        $.post(baseURL+"ajax.php", { tool: "vouchers", action: "check_voucher", voucher_code: voucher_code },
            function(data) {
            if(data == 'invalid'){
                // NEED TO RETURN FALSE FOR THE MAIN FUNCTION
            }
        });

}

Upvotes: 1

Views: 1853

Answers (4)

aepheus
aepheus

Reputation: 8187

The $.post is asynchronous as mentioned. As such, the function where you want to return false is actually executing after the main function (check_options) completes execution (and returns). I would suggest modifying your flow of control to account for an asynchronous call, or make the call synchronous (there should be an additional param, "async" I believe).

$.post({async:false, ...);

Upvotes: 0

Trey
Trey

Reputation: 5520

function check_options(){       
  var voucher_code = $('#voucher_code').val();
  $.ajax({
    type: 'POST',,
    url: baseURL+"ajax.php",
    data: { tool: "vouchers", action: "check_voucher", voucher_code: voucher_code },
    success: function(msg){
      alert('Success!');
    },
    error:function(e){
      alert('Fail!');
    }
  });
}

Upvotes: 0

Robert
Robert

Reputation: 21388

You can't return false for the main function because it's already processed by the time the ajax call completes. You'll need to use callbacks.

function check_options(callback) {
    var voucher_code = $('#voucher_code').val();
    $.post(baseURL + "ajax.php", {
        tool: "vouchers",
        action: "check_voucher",
        voucher_code: voucher_code
    }, function(data) {
        if (data == 'invalid') {
            callback && callback(false);
        } else {
            callback && callback(true);
        }
    });

}

check_options(function(result) {
    // Handle True/False based on result
});

Upvotes: 4

carlosfigueira
carlosfigueira

Reputation: 87228

You can't return false for the main function, because the post call is asynchronous. The function will return immediately after the $.post call, now when the response arrives. When the network call returns, then the function passed in the parameter will be invoked, but at that point the main function will have been long finished.

Basically, you're trying to do a synchronous network call, and there is no way to do that in JS.

Upvotes: 2

Related Questions