简体   繁体   English

检查用户名可用性ajax

[英]Check username availability ajax

As the title says, I am trying to check if a username exists in the DB in a registration form using Ajax. 如标题所示,我正在尝试使用Ajax检查用户名是否以注册形式存在于数据库中。

I use the following script: 我使用以下脚本:

    $(document).ready(function() {

    //the min chars for username
    var min_chars = 3;

    //result texts
    var characters_error = 'Minimum amount of chars is 3';
    var checking_html = 'Checking...';

    //when button is clicked
    $('#user_id').keyup(function(){
        //run the character number check
        if($('#user_id').val().length < min_chars){
            //if it's bellow the minimum show characters_error text '
            $('#username_availability_result').html(characters_error);
        }else{
            //else show the cheking_text and run the function to check
            $('#username_availability_result').html(checking_html);
            check_availability();
        }
    });

});

//function to check username availability
function check_availability(){

    //get the username
    var user_id = $('#user_id').val();

    //use ajax to run the check
    $.post("db.php", { user_id: user_id },
        function(result){
            //if the result is 1
            if(result == 1){
                //show that the username is available
                $('#username_availability_result').html(user_id + ' is Available');
            }else{
                //show that the username is NOT available
                $('#username_availability_result').html(user_id + ' is not Available');
            }
        });

}

and my db.php file looks like this: 和我的db.php文件看起来像这样:

if (isset($_POST['action']) && $_POST['action'] == "signup") {
$user_id      = mysql_real_escape_string($_POST["user_id"]);
$new_password = md5(mysql_real_escape_string($_POST["new_password"]));
$new_email    = mysql_real_escape_string($_POST["new_email"]);
$checking_existance=mysqli_query($str,"SELECT username FROM users WHERE username='".$user_id."'");
$row=mysqli_fetch_assoc($checking_existance);
print_r($checking_existance);
if(mysqli_num_rows($checking_existance)>0)
 {
    echo 0;
 }
else{
    echo 1;
}

} }

The problem I am encountering is that the result is always showing that the username is not available even if it is. 我遇到的问题是结果始终显示该用户名不可用,即使该用户名也不可用。

我发现这对您有用。您可以在以下链接上找到解决方案,请单击此处此处

Your db file is looking for a number of $_POST variables that you have not passed in. 您的db文件正在寻找许多尚未传递的$_POST变量。

action, new_password and new_email

I would guess that if you did console.log(result) you would get undefined , therefore its not = 1 and therefore goes into the else statement. 我猜想如果您做了console.log(result) ,则会得到undefined ,因此其not = 1 ,因此进入else语句。

You need to change the AJAX call to: 您需要将AJAX调用更改为:

$.post("db.php", { 
  user_id: user_id, 
  action: action, 
  new_password: new_password,
  new_email: new_email
}, ...

just do it in an easy way (i found that there is no action, new_password and new_email parameters in your javascript ) please take care of that too. 只需以一种简单的方式即可完成操作(i found that there is no action, new_password and new_email parameters in your javascript )请也注意这一点。

Javascript Java脚本

var min_chars = 3;
var characters_error  = 'Minimum amount of chars is 3';
var checking_html = 'Checking...';
var xhr_request = false;
var usernames = {};

$(function() {
  $("#user_id").on("keyup", check_availability );
});

function check_availability() {
  if ( xhr_request ) {
    xhr_request.abort();
  }
  var user_id = $.trim( $(this).val() );
  if ( !user_id || user_id.length < min_chars ) {
    $("#username_availability_result").html( characters_error );
    return;
  }

  // check user_id exists in runtime cache, to avoid useless requests :\
  if ( usernames[user_id] !== undefined ) {
    if ( usernames[user_id] === true ) {
      //show that the username is available
      $("#username_availability_result").html( user_id+" is Available" );
    }
    else {
      //show that the username is NOT available
      $("#username_availability_result").html( user_id+' is not Available' );
    }
    return;
  }

  //use ajax to run the check
  xhr_request = $.post( "c.php", { 'action' : 'validate', 'user_id' : user_id } );
  xhr_request.success(function( result ) {
    //if the result is 1
    if ( result == 1 ) {
      // add user_id to cache
      usernames[user_id]  = true;
      //show that the username is available
      $("#username_availability_result").html( user_id+" is Available" );
    }
    else {
      // add user_id to cache
      usernames[user_id]  = false;
      //show that the username is NOT available
      $("#username_availability_result").html( user_id+' is not Available' );
    }

  });
  xhr_request.fail(function() {
    $("#username_availability_result").html( "connection error, please try again" );
  });
}

PHP 的PHP

<?php
  if ( isset( $_POST["action"] ) && isset( $_POST["user_id"] ) ) {
    $mysqli = new mysqli( "localhost", "my_user", "my_password", "my_db" );
    $userid = $mysqli->real_escape_string( $_POST["user_id"] );

    if ( $_POST["action"] === "validate" ) {
      $result = $mysqli->query( "SELECT username FROM users WHERE username = '{$userid}'" );

      if ( $result && $result->num_rows > 0 ) {
        echo "0";
      }
      else {
        echo "1";
      }
    }
    elseif ( $_POST["action"] == "signup" ) {
      // do the process
    }
  }
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM