I have this JQuery
script which sends a request to check_username.php
which then checks in my database if the username is available and echoes back true
or false
and it's all working.
However when I type into my form a username which doesn't exists the form turns green, which is good, but once I enter a username which exists it turns the form red and then no matter what username I type it will always stay red.
How to solve this?
jquery
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
$(document).ready(function() {
$("#username").keyup(function(e) {
var username = $("#username").val();
$.post('check_username.php', {'username': username}, function(data) {
if(data=="true") {
$("#usergroup").addClass("input-group has-error");
} else if(data=="false"){
$("#usergroup").addClass("input-group has-success");
}
});
});
});
</script>
check_username.php
<?php
include 'includes\\connect.inc.php';
if(isset($_POST['username'])) {
$username = $_POST['username'];
$query = "SELECT id FROM users WHERE username='$username'";
$query_run = mysql_query($query);
if($query_run) {
$query_num_rows = mysql_num_rows($query_run);
if($query_num_rows==1) {
echo "true";
} elseif($query_num_rows==0) {
echo "false";
}
}
}
?>
connect.inc.php
<?php
$mysql_error = mysql_error();
$mysql_database = 'codeforum';
$mysql_host = '127.0.0.1';
$mysql_user = 'root';
$mysql_pass = '';
if(!mysql_connect($mysql_host, $mysql_user, $mysql_pass) || !mysql_select_db($mysql_database)) {
die($mysql_error);
}
?>