0

I ran this function when I click off the username input:

function checkUsername(){
    if($("#signupUsername").val()!=""){
        $.post("checkUsername.php",$("#signupForm :input").serializeArray(),function(data){
            if(data){
                $("#signupUsernameOutput").text("Username Taken");
                $("#signupUsernameOutput").css("color","#CE0000");
                return false;       
            }
            else{
                $("#signupUsernameOutput").text("Username OK");
                $("#signupUsernameOutput").css("color","green");                
                return true;
            }
        });
    }
    else{
        $("#signupUsernameOutput").text("");
        return false;   
    }
}

using:

<input type="text" class="form-control" onblur="checkUsername()" placeholder="Username" name="signupUsername" id="signupUsername">

My issue I need to run the same function later on from an If statement it doesn't work. Does anyone know why?:

if(checkUsername()==true){
       alert("success!");
       //and some other stuff...
}
Archer56
  • 15
  • 3
  • 1
    You're missing a `)`. Is that in your original code or just a copying error? – Barmar Feb 01 '14 at 01:18
  • possible duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Pointy Feb 01 '14 at 01:18
  • apologies as Barmar pointed out there was a copy error which I have corrected – Archer56 Feb 01 '14 at 01:22
  • How can you accidentally remove a bracket from the middle of your code when pasting it here? – Lee Taylor Feb 01 '14 at 01:25
  • if(checkUsername()==true) equals is redundant :) it's just code style suggestion. – Eugene P. Feb 01 '14 at 01:25
  • I was performing another check in the if statement. but it's unrelated to the issue. I have tested as pasted above. – Archer56 Feb 01 '14 at 01:26
  • I did think ==true was pointless doing but it wasnt returning as expected so I shoved it in there for the luls – Archer56 Feb 01 '14 at 01:27

2 Answers2

2

The function you are calling sends an asynchronous AJAX request. That is not going to work. It will get the AJAX request ready to go, and then it will return undefined, it will not return true in any situation.

You may want to think about changing your code, and adding code for a "promise". http://api.jquery.com/jQuery.post/

RustyToms
  • 7,600
  • 1
  • 27
  • 36
0

Besides the fact that you forgot a ), the function that executes when $.post() is complete is Asynchronous, so at the time you call checkUsername the completion function has not fired. Additionally you would be returning true or false to that function, not checkUsername. In short, everything has to happen inside your completion function, and it won't do any good to return anything. You can, however, change HTML inside the completion function.

StackSlave
  • 10,613
  • 2
  • 18
  • 35