Reputation: 497
I'm trying to use javascript validation for a simple login form. Right now I'm just focusing on the username input (Want it to display as red and have the error below it "That username is already taken" if the username is already taken). However, nothing shows up when the input is changed even though when I did inspect element network I saw that it was going to the registerjs.php file
In the head of the html form page i have
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
function valusername() {
var username = $('input#username').val();
if ($.trim(username) != '') {
$.post('../ajax/registerjs.php', {username: username}, function(data) {
if (data == 'That username is already taken') {
document.getElementById("username").style.border="3px solid red";
$('div#username_error').text(data);
}
});
}
}
</script>
The actual text input is
<input class="input" type="text" tabindex="1" placeholder="Username*"
style="height:20px;" name="username" id="username" onchange="valusername()">
<div id="username_error"></div>
The php file registerjs.php that is linked I'm sure works
<?php
include('../init.php');
if (isset($_POST['username']) === true && empty($_POST['username']) === false) {
$username = $_POST['username'];
if (user_exists($username) === true) {
echo("
That username is already taken
");
} else {
echo("Good");
}
}
?>
Does anyone know why I'm having this problem? It seems to be the if statement in the script.
Upvotes: 0
Views: 192
Reputation: 54050
Better Approach:
<input class="input" type="text" tabindex="1" placeholder="Username*"
style="height:20px;" name="username" id="username" >
<div id="username_error"></div>
<script>
$(function(){
$(document).on('change paste','#username', function () {
var username = $(this).val();
if ($.trim(username) !== '') {
$.post('../ajax/registerjs.php', {username: username},
function(data){
if (data) {
$("#username").css({'border','3px solid red'});
$('div#username_error').text('Username already exist');
return false;
}
}
); // end of $.post
} // end of if
})
})
</script>
<?php
include('../init.php');
// here i assume user_exists return true or false
if ( !empty($_POST['username']) && user_exists($username)) {
return TRUE;
}
else{
return FALSE;
}
?>
Upvotes: 1
Reputation: 3133
Do this :
function valusername()
{
var username = $('input#username').val();
if ($.trim(username) != '')
{
$.post('../ajax/registerjs.php', {username: username}, function(data)
{
if ($.trim(data) == 'That username is already taken')
{
document.getElementById("username").style.border="3px solid red";
$('div#username_error').text(data);
}
});
}
}
Upvotes: 2