I am trying to create 3 conditions in Ajax to check when creating a new user id. It works for 2 conditions (username can be used and username is already in use), but I encounter a problem when the user leaves the username field empty, and it still displays "username can be used". I attempted to use
if(data == "")
, but it did not work. Can anyone help me please? I apologize for being a beginner in JavaScript and still learning.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#username').change(function(e){
$('#pesan').html("<img src='loading.gif' />checking...");
var username = $('#username').val();
$.ajax({
type:"POST",
url:"chk2.php",
data:"username="+username,
success: function(data){
if(data == "")
{
$('#pesan').html("<img src='failed.png' /><span style='color:green;margin-left:10px;'>Cannot Be Empty!!!</span>");
}
else
{
if(data == 0){
$('#pesan').html("<img src='accept.png' /><span style='color:green;margin-left:10px;'>Username can be used</span>");
} else {
$('#pesan').html("<img src='failed.png' /><span style='color:red;margin-left:10px;'>Username is already in use</span>");
}
}
}
});
});
});
</script>
</head>
<body>
<table>
<form>
<tr>
<td><label for="username">Username</label></td>
<td>:</td>
<td><input type="text" size="20" name="username" id="username"/></td>
<td><span id="pesan"></span></td>
</tr>
<tr>
<td><label for="password">Password</label></td>
<td>:</td>
<td><input type="password" size="20" name="password" id="password"/></td>
</tr>
<td><input type="submit" value="submit" name="submit" /></td>
</form>
</table>
</body>
</html>
for chk2.php
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("ptmjp");
$username = $_POST['username'];
$sql = mysql_query("select code_item from stock where code_item='$username'");
$find = mysql_num_rows($sql);
echo $find;
?>