开发者

jQuery get function to return true/false

$(document).ready(function(){
 //global vars
 var name = $("#username");
    var email = $("#email");


 function usernameExists() {
  $.get("register.php",{ check: 1, username: name.val(), email: email.val() } ,function(m) {
      if(m==1) {
     return false;
    } else { 
     return true;
    }
  });
 }
});

Firebug shows the right response when this function is being called, however it returns nothing...(this $.get(...) function has been tested outside the function usernameExists() but without the returns and it worked perfectly).

What's the problem and how to solve?


     $(document).ready(function(){
    //global vars
    var form = $("#register");
    var name = $("#username");
    var email = $("#email");

     $.get("register.php",
             { check: 1, username: name.val(), email: email.val() },

               // Have this callback take care of the rest of the submit()
             function(m) {
                if(m==1) {
                     form.submit(function(){ return false; });
                } else {
                    form.submit(function(){
        if(validateName() & validateEmail() & validatePass1() & validatePass2())
   开发者_开发技巧         return true
        else
            return false;
                });
             }

         }
      );

function validateName(){
        // some check here
    }

// and other functions

});


The function you're calling doesn't return anything.

Even if it did try to return the response from your $.get(), it wouldn't work because the call is asynchronous, so by the time the response has been received, whatever code that would have used the return value has likely already executed.

What you need to do is call your code from within the $.get() callback.

function usernameExists() {
    $.get("register.php",{ check: 1, username: name.val(), email: email.val() } ,function(m) {
            someOtherFunction(m==1);
    });
}

function someOtherFunction(parameter) {
    // The parameter will be true or false
    //    depending on the value of m==1
}

Updated based on your comment.

Probably better just to bring the $.get() into the submit(), but keeping true to your original idea, this is how it could look.

form.submit(function(){
       // After usernameExists() is called, we need to hand off
       //    the rest of the execution to that function since
       //    this one will be done executing before the get()
       //    response is received
    usernameExists();
    return false;
}); 

function usernameExists() {
    $.get("register.php",
             { check: 1, username: name.val(), email: email.val() },

               // Have this callback take care of the rest of the submit()
             function(m) {
                if(m==1) {
                     // do something if true
                } else {
                     // do something if false
                }
             }
      );
}

Explanation of the joys of synchronous vs. asynchronous javascript

Javascript code normally executes synchronously. That just means that it executes one line at a time, or one line must finish executing before the next line can fire.

var greeting = "hi there";  // set the greeting variable

alert( greeting );   // the alert won't fire,
                     //    until the previous line finished successfully

This makes things very nice and predictable. But there are some exceptions to that rule. One notable exception is AJAX calls.

Your $.get() is an example of an AJAX call. The "A" in AJAX stands for asynchronous, which means that it does not prevent the next line of code from executing.

The ramification is that when you do a $.get() that takes (for example) 1 second to complete, whatever code came after the $.get() has long since finished by the time the $.get() has received its response.

Take the previous greeting example, but this time using AJAX.

var greeting;  // will hold the response from our AJAX call

$.get('some/path/to/data.php', 
         function( m ) {
             greeting = m;  // populate the greeting variable with the data returned
         }
);

alert( greeting );   // Will alert "undefined" instead of the data that was returned
                     //   because the $.get() code above is asynchronous, which allows
                     //   the code below it (the alert in this case) to continue 
                     //   executing.

As you can see, the alert( greeting ) would have executed long before the $.get() response was received, because he $.get() is asynchronous, and doesn't pause the execution chain while it is waiting for its data.

To resolve this, you would place the alert() inside the callback for $.get(), so that it won't run until the response is received.

var greeting;  // will hold the response from our AJAX call

$.get('some/path/to/data.php', 
         function( m ) {
             greeting = m;  // populate the greeting variable with the data returned
             alert( greeting );  // Now the alert will give the expected result
                                 //    because it is in the callback.
         }
);

The upshot is that in your code, once you call $.get(), any remaining code that relies on the response received should take place inside the callback.

The only way to place your code outside the callback would be to place it in its own function that gets called from inside the callback (like I did with my original answer).


Basic layout of how your code should operate:

Keep in mind, that you don't necessarily need a separate function for usernameExists(). You could place all that code inside the submit()

form.submit(function() {
       // Check to make sure input is valid **before** you send the AJAX
    if(validateName() & validateEmail() & validatePass1() & validatePass2()) {
        usernameExists();  // If valid, continue with the usernameExists()
    }
    return false; // We return false whether or not the content was valid,
                  //   in order to prevent the form from submitting prematurely
}); 

function usernameExists() {
    $.get("register.php",
             { check: 1, username: name.val(), email: email.val() },

               // Have this callback take care of the rest of the submit()
             function(m) {
                   // If "m" is less than one, there were no existing users
                   //    so we can go ahead and post the data to the server
                if( parseInt(m) < 1 ) {
                     // Here, you would need to manually do a post to 
                     //   submit the data to the server
                     $.post(url, data, callback, datatype );
                }
             }
     );
}

http://api.jquery.com/jquery.post/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜