1

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

}
1
  • Have you thought about using a jQuery form validation plugin such as jquery.validate? Commented Jun 1, 2011 at 17:59

4 Answers 4

4

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
});
Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

You can make synchronous network calls, it's just a terrible idea.
0
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!');
    }
  });
}

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.