admin管理员组

文章数量:1431426

I want to check if the username is taken before the form is submitted.

As far as I can understand I have to use AJAX to get data from my database in javascript. How do I send the username to the PHP file?

This is my form:

<form id="loginForm" action="register.php" method="post">
    <p>Register:</p>
    <p style="text-align: left;">Full name: <br><input type="text" name="name" required/></p>
    <p style="text-align: left;">Email: <br><input type="text" name="email" required/></p>

    //Username
    <p style="text-align: left;">Username: <br><input id="username" type="text" name="username" onkeyup="validateUsername(value);" required/></p>
    <span id="usernameError" style="display:none;border:1px solid red;">Username can only contain a-z, 0-9 and must be at least 6 characters loong</span>
    <span id="usernameTaken" style="display:none;border:1px solid red;">Username taken</span>

    <p style="text-align: left;">Password: <br><input type="password" name="password" required/></p>
    <input type="submit" value="Register">
</form>

I want to check if the username is taken before the form is submitted.

As far as I can understand I have to use AJAX to get data from my database in javascript. How do I send the username to the PHP file?

This is my form:

<form id="loginForm" action="register.php" method="post">
    <p>Register:</p>
    <p style="text-align: left;">Full name: <br><input type="text" name="name" required/></p>
    <p style="text-align: left;">Email: <br><input type="text" name="email" required/></p>

    //Username
    <p style="text-align: left;">Username: <br><input id="username" type="text" name="username" onkeyup="validateUsername(value);" required/></p>
    <span id="usernameError" style="display:none;border:1px solid red;">Username can only contain a-z, 0-9 and must be at least 6 characters loong</span>
    <span id="usernameTaken" style="display:none;border:1px solid red;">Username taken</span>

    <p style="text-align: left;">Password: <br><input type="password" name="password" required/></p>
    <input type="submit" value="Register">
</form>

This is the validateUsername() function:

function validateUsername(username) {
    var re = /[a-zA-Z0-9]/;
    alert(username.length);
    if(re.test(username) && username.length > 5) {
        document.getElementById('username').style.backgroundColor = "green";
        document.getElementById('usernameError').style.display= "none";
        --error;
    } else {
        document.getElementById('username').style.backgroundColor = "red";
        document.getElementById('usernameError').style.display= "block";
        ++error;
    }
    //here i want to check if the user name is taken
}

If the username is taken, I want to display the 'usernameTaken' span. Otherwise, I want to hide it.

Here is the PHP file that checks if the username is already in the database:

<?php
session_start();
define('DB_NAME', 'madsanker_dk_db');
define('DB_USER', 'madsanker_dk');
define('DB_PASSWORD', 'MyPassword');
define('DB_HOST', 'mysql43.unoeuro.');

$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);

if (!$link) {
    die('Could not connect: ' .mysqli_error());
}

$db_selected = mysqli_select_db( $link, DB_NAME);

if (!$db_selected) {
    die('Could not connect: ' .mysqli_connect_error());
}

$username = //The username;
$username = mysqli_real_escape_string($link,$username);

$sql = "SELECT * FROM mainLogin WHERE username = '$username'";

$result = mysqli_query($link, $sql);
$count = mysqli_num_rows($result);

if($count == 0) {
    //if the username is NOT taken
    return true;
} else {
    //if the username IS taken
    return false;
}
mysqli_close($link);
?>

How is this done?

Share Improve this question edited Jan 22, 2018 at 8:22 Manoj Kadolkar 7168 silver badges22 bronze badges asked Mar 6, 2016 at 11:42 Mads NielsenMads Nielsen 1061 gold badge5 silver badges14 bronze badges 3
  • U can use ajax send username to Php by using element id or jquery – devpro Commented Mar 6, 2016 at 11:45
  • where is your problem in this code? Have you tested that username goes in ajax request correctly. – K. Uzair Commented Mar 6, 2016 at 11:46
  • The PHP should return a document of some kind, it's not a function return. The most simple example would be to just print "true" or "false". The a -jax call is a -synchronous, so disable the submit button in the verify function and then re-enable it when the callback from the ajax says all is good e.g. if (this.response === "true"); (or after some reasonable timeout, e.g. 2 seconds) – Paul S. Commented Mar 6, 2016 at 11:47
Add a ment  | 

2 Answers 2

Reset to default 2

JS - JQUERY AJAX

$.ajax({ 
    url: 'register.php', data: {action: 'isUserNameTaken', params: [username]},
    type: 'post',
    success: function(data) {
        //Do Something
    }
});

PHP

<?php
function isUserNameTaken($username) {
    //Do Something;
}

if(!empty($_POST['action'])) {
    $action = $_POST['action'];
    switch($action) {
        case 'isUserNameTaken':
            $username = '';

            if(!empty($_POST['params'])) {
                $username = $_POST['params'][0];
            }

            isUserNameTaken($username);

            break;
    }
}
?>

You could do it this way: On client side:

function validateUsername(){
   if(//test username input for length...) {
   $.ajax({  
         type: 'POST',  
         url: 'validate.php', 
         data: { username: username },
         success: function(response) {
              if(response==0){
                 //username is valid
               }
              elseif(response==1){
               //username is already taken
              }
              elseif(response==2){
                //connection failed 
              }

         }
   });
  }
  else{
     //display "username is too short" error
  }

}

validate.php:

<?php
session_start();
define('DB_NAME', 'madsanker_dk_db');
define('DB_USER', 'madsanker_dk');
define('DB_PASSWORD', 'MyPassword');
define('DB_HOST', 'mysql43.unoeuro.');

$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);

if (!$link) {
  die('Could not connect: ' .mysqli_error());
   echo json_encode(2);
}
 else{
   $db_selected = mysqli_select_db( $link, DB_NAME);

   if (!$db_selected) {
      die('Could not connect: ' .mysqli_connect_error());
       echo json_encode(2);
    }
    else{
       $username = $_POST["username"];
       $username = mysqli_real_escape_string($link,$username);

       $sql = "SELECT * FROM mainLogin WHERE username = '$username'";

       $result = mysqli_query($link, $sql);

       $count = mysqli_num_rows($result);
       if($count == 0) {
         //if the username is NOT taken
         echo json_encode(0); 
       }else {
          //if the username IS taken
             echo json_encode(1);
        }
        mysqli_close($link);
    }


 }

?>

You can also make this function validateUsername by calling it with onkeyup function in jquery so every time a user types something into the input field, the username will be checked....

本文标签: javascriptChecking if username is available before submitting a formStack Overflow