tags:

views:

81

answers:

1
$(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

});
+4  A: 

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/

patrick dw
Thanks. But if i want to check if the function returns true or false which one i call? i suggest the first one?(Updated the question code)And still that returns false
cthulhu
@cthulhu - That won't work because `usernameExists()` doesn't return anything. And event if it did, the `if()` statement in your `submit()` would be done executing before the response would be received. Basically, what you need to do is keep *any and all* code that relies on the response from your `$.get()` inside the callback. Or call another function from inside the callback, like my answer. I'll update my answer with another solution.
patrick dw
still it returns false...
cthulhu
@cthulhu - You need to understand, you *must not* try to return a value from the `usernameExists()` function. It simply won't work. You must do the remainder of your code execution *inside* that function. If you're not understanding why that is, let me know, and I'd be happy to give you a different example that may explain better.
patrick dw
yes please give an example..i'm just new to jquery stuff, so i want to understand better how it works..
cthulhu
@cthulhu - Not a problem. :o) I'll update my answer in a few minutes with an example at the bottom that more fully describes the issue.
patrick dw
thanks for your detailed explanation...i did this with variable like in your example...(updated the code). But now one little problem...when i want to send the form i need to click the button of submit twice...can you take please a look at the new code?thanks in advise :)
cthulhu
patrick dw
i understood..i just tried some different ways...but it really works now..so how?
cthulhu
patrick dw
ok, so according to your example the form.submit check should be inside the $.get.
cthulhu
@cthulhu - If you mean the long `if()` statement, then yes, it should take place *after* the data has been received from `$.get()`. The only way to accomplish that is to place it *inside* the callback for `$.get()`.
patrick dw
Ok. I tried this (updated the code), and it looks like there is no return at all. The form is not sent at all...false is returned always probably.omg such a little thing and so much problems...
cthulhu
@cthulhu - No, the `$.get()` call still needs to be *inside* `form.submit(...)`. It is the `if()` statement that needs to be inside the `$get()` callback. And because the `submit()` is no longer able to finish executing (because it needs to wait for the `$.get()`), you need to manually post the data to your server. I'll add an example to the bottom of my answer.
patrick dw
Thank you very much!
cthulhu
@cthulhu - You're welcome. :o)
patrick dw