views:

341

answers:

3

Hello! 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;
});

});

+1  A: 

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 :)

Nick Craver
sorry :( it didn't work, returns false. I've changed success callback function into: if ( $("message", xml).text() == "Available" ) return true; else return false;
abdullah kahraman
@abdullah - There is no difference in that `return` function, just extra code...if the answer you posted works but this one doesn't then the php file in your question is not accurate and you should update it.
Nick Craver
@Nick: I think the problem was the return of the dummy function in the parameter after "checkAvailability", which is function(value,element){}. Actually, it returned nothing~=false, right? It just did some ajax function that returned some value. But "the function(value,element)" didn't return anything itself. I am a beginner, just my thoughts though :)
abdullah kahraman
@abdullah - That's about what happened, it wasn't returning so the result is `undefined` as I said in the answer above, anything that's not `true` fails validation. Also make sure to accept an answer if it resolved your issue!
Nick Craver
+1  A: 

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;
});
});
abdullah kahraman
A: 

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");
Dmitry
so if it returns true, it eval will return boolean true, and if it returns false, eval will return boolean false. right?
abdullah kahraman
yes, that's correct!
Dmitry