views:

150

answers:

1

Hi,

I read your reply regarding the jQuery validator where you outline a method to check a username against a value in a database.

Ive tried implementing this method but no matter what is returned from the PHP file I always get the message that the username is already taken.

Here is ths custom method...

$.validator.addMethod("uniqueUserName", function(value, element) {
  $.ajax({
      type: "POST",
       url: "php/get_save_status.php",
      data: "checkUsername="+value,
      dataType:"html",
   success: function(msg)
   {
      // if the user exists, it returns a string "true"
      if(msg == "true")
         return false;  // already exists
      return true;      // username is free to use
   }
 })}, "Username is Already Taken");

And here is the validate code...

username: {
required: true,
uniqueUserName: true

},

Is there a specific way i am supposed to return the message from php.

Thanks

A

A: 

You are doing an AJAX request, ergo: the validation is already finished working when your custom validator returns either true or false.

You will need to work with async. See also this post: http://stackoverflow.com/questions/133310/how-can-i-get-jquery-to-perform-a-synchronous-rather-than-asynchronous-ajax-req

Something like:

function myValidator() {
   var isSuccess = false;

   $.ajax({ url: "", 
            data: {}, 
            async: false, 
            success: 
                function(msg) { isSuccess = msg === "true" ? true : false }
          });
    return isSuccess;
}
Jan Jongboom
Thanks. Your answer worked a treat!
thatweblook