开发者

jQuery AJAX callback

开发者 https://www.devze.com 2023-03-10 05:20 出处:网络
I\'m having a difficult time trying to get this javascript function to return false inside of a .post() function.

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

}


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


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.


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!');
    }
  });
}


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, ...);
0

精彩评论

暂无评论...
验证码 换一张
取 消