Oldook
Oldook

Reputation: 109

JQuery validation custom method trouble

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.

Upvotes: 1

Views: 116

Answers (1)

Ryley
Ryley

Reputation: 21216

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();
               }
            }
        }
    }
});

Upvotes: 2

Related Questions