Cont on AJAX live checking availability with submit button && AJAX live checking availability with submit button (part 2)
functions.php
<?php
function AddUserForm()
{
?>
<form id="adduser" name="adduser" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
Username: <input type="text" id="username" name="username" size="30" maxlength="50" /><span id="usernameCheck"></span><br /><br />
<input type="submit" name="submit" value="Add User" />
<input type="reset" name="reset" value="Reset" />
</form>
<script language="JavaScript" type="text/javascript">
var frmvalidator = new Validator("adduser");
frmvalidator.addValidation("username","req","Please fill up the username.");
</script>
<?php
}
?>
adduser.php
<?php
include_once('functions.php');
?>
<html>
<head>
<script language="JavaScript" src="formvalidator2.js"></script>
<script type="text/javascript" src="js/jquery-1.11.1.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.11.1/jquery-ui.js"> </script>
<link rel="stylesheet" href="js/jquery-ui-themes-1.11.1/themes/smoothness/jquery-ui.css">
<script type="text/javascript">
$(document).ready(function(){
var a = false;
$('#username').change(function(){
var userName = $('#username').val();
if(userName == "")
{
$("#usernameCheck").empty();
}
else
{
$.post("getUserName.php", {userName: userName}, function (data)
{
a = data;
$("#usernameCheck").html(data);
});
}
});
//---[1]---
$('#adduser').submit(function(){
return a == 'username valid';
});
});
</script>
</head>
<body>
<?php
AddUserForm();
//---[2]---
if(isset($_POST['submit']) && ($_POST['submit'] == 'Add User'))
{
echo $_POST['username'];
}
?>
</body>
</html>
getUserName.php
<?php
$dbc = mysqli_connect('localhost', 'root', '', 'usertest') OR die(mysqli_connect_error());
$userName = $_POST['userName'];
$q = "select user_name from user where user_name = '".$userName."'";
$r = mysqli_query($dbc, $q);
$num = mysqli_num_rows($r);
if($num)
{
echo 'username invalid';
}
else
{
echo 'username valid';
}
?>
Here is my requirements:
(1) If user not fill in username
- Form validator will pop out the message "Please fill up the username message".
(2) If user fill in a user name not same with the database
- Show "Username valid" besides the username field.
- Will display username after click the "Add User" button.
(3) If user fill in a user name same with the database
- Show "Username invalid" besides the username field.
- Will not submit form after click the "Add User" button.
From my above code, I discovered that [1] will submit the form.
On the other hand, [2] will also submit the form.
I don't want multiple submit form run in my web page.
Is there any way to fulfill my requirements in single submit form?
Can someone assists me?
