Home » Php » php – .post inside jQuery.validator.addMethod always returns false

php – .post inside jQuery.validator.addMethod always returns false

Posted by: admin July 12, 2020 Leave a comment

Questions:

I am very new to jQuery and javascript programming. I have a program below that checks whether username is taken or not. For now, the PHP script always returns

  if(isset($_POST["username"]) )//&& isset($_POST["checking"]))
    {
        $xml="<register><message>Available</message></register>";
        echo $xml;
    }

Login function works, but username checking doesn’t. Any ideas?
Here is all of my code:

$(document).ready(function() {
jQuery.validator.addMethod("checkAvailability",function(value,element){
    $.post( "login.php" , {username:"test", checking:"yes"}, function(xml){
        if($("message", xml).text() == "Available") return true;
        else return false;
    });
},"Sorry, this user name is not available");
$("#loginForm").validate({
    rules:  {
        username: {
            required: true,
            minlength: 4,
            checkAvailability: true
        },
        password:{
            required: true,
            minlength: 5
        }
    },
    messages: {
        username:{
            required: "You need to enter a username." ,
            minlength: jQuery.format("Your username should be at least {0} characters long.")
        }
    },
    highlight: function(element, errorClass) {
                $(element).fadeOut("fast",function() {
                $(element).fadeIn("slow");
                })
    },
    success: function(x){
        x.text("OK!")
    },
    submitHandler: function(form){send()}
});
function send(){
    $("#message").hide("fast");
    $.post( "login.php" , {username:$("#username").val(), password:$("#password").val()}, function(xml){
        $("#message").html( $("message", xml).text() );
        if($("message", xml).text() == "You are successfully logged in.")
        {
            $("#message").css({ "color": "green" });
            $("#message").fadeIn("slow", function(){location.reload(true);});
        }
        else
        {
            $("#message").css({ "color": "red" });
            $("#message").fadeIn("slow");
        }
    });
}
$("#newUser").click(function(){

    return false;
});

});

How to&Answers:

You need to use the expanded form of $.post() which is $.ajax() so you can set the async option to false, like this:

jQuery.validator.addMethod("checkAvailability",function(value,element){
    $.ajax({
      url: "login.php",
      type: 'POST',
      async: false,
      data: {username:"test", checking:"yes"},
      success: function(xml) {
        return $("message", xml).text() == "Available";
      }
    });
},"Sorry, this user name is not available");

Currently your success function that analyzes the response happens after the validation finishes, because it’s an asynchronous operation. So currently, it’s not returning anything at the time the return value is used, and undefined ~= false, which is why it always appears false. By setting async to false, you’re letting the code execute in order without the callback, so the return in the example above is actually used.

Another alternative, if you can adjust your page’s return structure is to use the validation plugin’s built-in remote option, which is for just this sort of thing 🙂

Answer:

It’s OK, and working now. Here is the code:

$(document).ready(function() {
jQuery.validator.addMethod("checkAvailability",function(value,element){
 var x= $.ajax({
    url: "login.php",
    type: 'POST',
    async: false,
    data: "username=" + value + "&checking=true",
 }).responseText;
 if($("message", x).text()=="true") return true;
 else return false;
},"Sorry, this user name is not available");
$("#loginForm").validate({
    rules:  {
        username: {
            required: true,
            minlength: 4,
            checkAvailability: true
        },
        password:{
            required: true,
            minlength: 5
        }
    },
    messages: {
        username:{
            required: "You need to enter a username." ,
            minlength: jQuery.format("Your username should be at least {0} characters long.")
        }
    },
    highlight: function(element, errorClass) {
                $(element).fadeOut("fast",function() {
                $(element).fadeIn("slow");
                })
    },
    success: function(x){
        x.text("OK!")
    },
    submitHandler: function(form){send()}
});
function send(){
    $("#message").hide("fast");
    $.post( "login.php" , {username:$("#username").val(), password:$("#password").val()}, function(xml){
        $("#message").html( $("message", xml).text() );
        if($("message", xml).text() == "You are successfully logged in.")
        {
            $("#message").css({ "color": "green" });
            $("#message").fadeIn("slow", function(){location.reload(true);});
        }
        else
        {
            $("#message").css({ "color": "red" });
            $("#message").fadeIn("slow");
        }
    });
}
$("#newUser").click(function(){

    return false;
});
});

Answer:

OK, this might not be all that relevant but I had a similar issue. I didn’t do anything with the return value, I just returned it. And it always was true. So, after some poking around I figured that the value from the server appeared as a String to the validator. So long as it was not an empty string it would return true. So the solution was to use eval();

An example:

jQuery.validator.addMethod("checkAvailability",function(value,element){
 return eval($.ajax({
    url: "/check",
    async: false,
    data: {
      field: $('#element').attr('name'),
      val: value
    }
 }).responseText);
}, "error");