Friday, February 27, 2009

[jQuery] Re: function $.ajax return true/false ?

The issue here is that AJAX is asynchronous. The the moment you're
checking pnrexists(ph), it'll execute the AJAX but nothing is returned
"at that moment" (which means it is not-true, so the if-statement
fails). Then a few milliseconds later, your AJAX response has
returned, but the code is way passed the if-statement by then already.
Try adding the 'async: true' to the $.ajax() option. This tells the
rest if your code to wait for the AJAX response before continuing.

On Feb 27, 8:00 am, Gelegrodan <GeleGro...@gmail.com> wrote:
> Hello
> I have the following code:
>
> function pnrexists(a){
>         $.ajax({
>                 url: '/inc/chkusr.php?q=p',
>                 type: 'POST',
>                 dataType: 'html',
>                 data: {'pnr': a},
>                 timeout: 2000,
>                 success: function(data) {
>                         if(data==1){
>                                 alert('true');
>                                 return true;
>                         }else{
>                                 alert('false');
>                                 return false;
>                         }
>                 },
>         });
>
> }
>
> the code above is triggered by:
>
> $.validator.addMethod("pnrcheck", function(ph, element) {
>         alert('1');
>         if(persnr(ph)) {
>                 alert('2');
>                 if(pnrexists(ph)) {
>                 alert('3');
>  the code continues..but noting to show...
>
> The problem is: I see:
> alert 1
> alert 2
> alert true
> but NOT alert 3?? Why?

No comments: