I am trying to check the user username when typing it in the signup form and I have created the following function:
function validateSignupEmail(input){
if (input == ""){
return "Please enter your usernane.";
}else if (input.length > 20){
return "Your username cant exceed 20 characters.";
}else{
var type = "username_check";
$.ajax({
type: "POST",
url: www+"signup/validate",
dataType: 'json',
data: {
type : type,
input : input
},
success: function(data) {
return data.response;
}
});
}
}
Inside the signup controller I have the following function called validate()
function validate(){
$type = isset($_POST["type"]) ? $_POST["type"] : "";
$input = isset($_POST["input"]) ? $_POST["input"] : "";
if ($type == "username_check"){
echo json_encode(array('response' => 'username available'));
}else{
return false;
}
}
Also I have the following code which shows what the username status in a div:
$("#signup_page form input[type='text']#username").keyup(function(){
var text = validateSignupEmail($(this).val());
console.log('text => '+text);
$(".signup_ajax_live_messages").find(".username_check").text(text);
})
The thing is that I can’t return the AJAX response inside the success: function(){}
Thanks.
Welcome to the wonderful world of async, where you have to wait for the AJAX call to complete before processing the response.
Here’s how you would process the response in your callback:
On a side note: Are you sure you want to make a new AJAX request on every single keystroke?
If you want to only check after the user has paused typing, use
setTimeout:Here’s an example: http://jsfiddle.net/dMhdD/