1

I'm using the JQuery validation plugin, and added a new method for check availability of name in the database. Php script works well and return 1 or 0 correctly. But the method always returns "Name is not available".

jQuery.validator.addMethod("loginAvailability", function(value, element) {

    $.post("CheckLogin.php", { login: value },
        function(result){
        console.log(result);
        console.log(value);
            return result;
        }
    )},"Name is not available");

There is console log( "abc" user in database ):

0
abc
1
qwe

That all works well, when we test that on xammp local server, but doesn't work on real server.

Sparky
  • 98,165
  • 25
  • 199
  • 285
Oldook
  • 107
  • 5
  • you cannot do it like that.... you are using a ajax request which is asynchronous so you cannot return a value from it... see http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call – Arun P Johny Dec 20 '13 at 13:20
  • You could try making the request synchronously: async: false – Gareth James Dec 20 '13 at 13:34

1 Answers1

2

As people commented - you cannot return the value of $.post because your loginAvailability function returns before the $.post does. Fortunately for you, jQuery Validate provides a remote method that takes care of this for you!

$('form').validate({
    rules: {
        username: {
            required:true,
            remote: {
               url: "CheckLogin.php",
               type:'post',
               data: {
                   login: function() {
                      return $( "#username" ).val();
               }
            }
        }
    }
});
Ryley
  • 21,046
  • 2
  • 67
  • 81