This is my html form I am using.
<label>Your Username:</label><input id="username" name="username" type="text" onchange="return ajax ('username');" />
This is my ajax checking file in php.
if ($_REQUEST['username']) {
$q = $dbc -> prepare("SELECT username FROM accounts WHERE username = ?");
$q -> execute(array($_REQUEST['username']));
if (strlen($_REQUEST['username']) < 3) {
echo '<div class="error">Has to be at least 3 characters</div>';
}
elseif ($q -> rowCount() > 0) {
echo '<div class="error">Username already taken</div>';
}
else {
echo '<div class="success">Username available</div>';
}
}
And my jquery ajax request...
function ajax (input) {
var val = $('#'+input).val();
$('.loading').fadeIn().delay(100);
$.post("ajax.php", {
username: val,
},
function (response) {
$('.error, .success').hide();
setTimeout(function(){
$('.loading').hide();
finishAjax(input, response);
}, 1000);
});
return false;
}
function finishAjax(id, response) {
$('#'+id).after(response).fadeIn(2000);
}
On my form I call the ajax request with the variable username.
In my ajax.php the correct validation of the username takes place if the request is named username.
I would like to display the variable input in place of username in the jquery code so I can use this script for other validations and pass the variable as email, or password and the script will still run as the value of input will be what it needs to be.
If that makes sense.
Thanks for your time.