使用提交按钮进行AJAX实时检查可用性(第3部分)

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 expected output:
enter image description here

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?

There are a few steps to reach your desired functionality...

  1. Listen for the focus event on the username

    $("#username").on('focus', function() { // Insert Blur Listener Here // Insert Keyup Listener Here });

    • Listen for the blur event on the username field

      • Make sure the value of the username field is not equal to ""

        • If it is equal to "", disable the submit button
        • If it is NOT equal to "", and the AJAX call reveals the username IS available... enable the submit button

          $("#username").on('blur', function() { if( $(this).val() === "" ) { // If username value is empty SHOW ERROR $("#usernameCheck").html("Username Required!"); } else { // Username field NOT empty, check username availability var userInput = $(this).val(); $.ajax({ url : "getUserName.php", method : "POST", data : { userName : userInput }, success : function(response) { if( response.indexOf("invalid") >= 0 ) { $("#usernameCheck").html("Username Already In Use!"); // Username IS NOT available } else { // Username IS available $("#usernameCheck").html("Username Available!"); } }, error : function(error) { // Handle PHP script errors here } }); } });

    • Listen for the keyup event on the username field
      • Utilizing an AJAX call search your database for the userName value
        • $("#username").on('keyup', function() { var userInput = $(this).val(); $.ajax({ url : "getUserName.php", method : "POST", data : { userName : userInput }, success : function(response) { if( response.indexOf("invalid") >= 0 ) { $("#usernameCheck").html("Username Already In Use!"); // Username IS NOT available } else { $("#usernameCheck").html("Username Available!"); // Username IS available } }, error : function(error) { // Handle PHP script errors here } }); });
  2. Listen for the submit event on the #addUser form, to perform a last second availability check

    • Prevent the default action
    • Run the AJAX call
      • On "valid", submit the form
      • On "invalid", show an error of some sort.
    • THIS WOULD BE USED IN CASE THE USER RELOADS THE PAGE AND THE USERNAME INPUT HAS A VALUE BUT WAS NOT FOCUSED
    • THIS WILL ALSO CAPTURE ALL FORMS OF SUBMISSION (i.e. clicks, enter keypress, etc. ) $("#addUser").on("submit", function(e) { e.preventDefault(); var userInput = $("#username").val(); $.ajax({ url : "getUserName.php", method : "POST", data : { userName : userInput }, success : function(response) { if( response.indexOf("invalid") >= 0 ) { $("#usernameCheck").html("Username Already In Use!"); } else { $("#addUser").submit(); } }, error : function(error) { // Handle PHP script errors here } }); });