jQuery 使用 AJAX 检查数据库中是否存在用户名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9762478/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 11:16:19  来源:igfitidea点击:

Check if username exists in database with AJAX

jqueryajaxjson

提问by Vdas Dorls

So basically, I want to add a feature to my registration form which I will check if that username already exists in the database.

所以基本上,我想在我的注册表单中添加一个功能,我将检查该用户名是否已存在于数据库中。

I have a few questions about AJAX -

我有几个关于 AJAX 的问题 -

1) I want to create an AJAX request on_change function, so something like this -

1)我想创建一个 AJAX 请求 on_change 函数,所以像这样 -

$('#username').change(function() {
  $.ajax({
  url: "validation.php"
  });
});

So, as far as I understood, I must have all validations made in PHP inside the validation.php file, correct? Is there any special validation needed or can it be just simple validation with a sql statement - SELECT * FROM 'users' WHERE 'username' = '. $_POST['username'];

因此,据我所知,我必须在validation.php 文件中使用PHP 进行所有验证,对吗?是否需要任何特殊验证,或者它可以只是使用 sql 语句进行简单验证 -SELECT * FROM 'users' WHERE 'username' = '. $_POST['username'];

2) So as I understood I must pass the POST values via $.ajax too, correct? If yes, how will I be able to access them via the validation.php file?

2)据我所知,我也必须通过 $.ajax 传递 POST 值,对吗?如果是,我将如何通过validation.php 文件访问它们?

3) After I get the results in validation.php file, how can I pass them back (true or false -- exists or doesn't exist)? I will need to pass them back, and then do an if check, if it's true - show an error that the username already exists, otherwise, don't show anything?

3) 在validation.php 文件中得到结果后,如何将它们传回(真或假——存在或不存在)?我需要把它们传回去,然后做一个 if 检查,如果它是真的 - 显示用户名已经存在的错误,否则,不显示任何内容?

Hope, you understood what I'm about to create. I know there are a lot of tutorials over the internet, but I don't like to create something via tutorials, since if I create it by myself, it will be easier to understand next time ;)!

希望,你明白我要创造什么。我知道网上有很多教程,但我不喜欢通过教程创建东西,因为如果我自己创建它,下次会更容易理解;)!

EDIT: In addition, I'm creating my website with CodeIgniter framework, so how would I pass the url attribute in ajax, to a CodeIgniter module?

编辑:此外,我正在使用 CodeIgniter 框架创建我的网站,那么我将如何将 ajax 中的 url 属性传递给 CodeIgniter 模块?

回答by Austin Brunkhorst

Before continuing, SELECT * FROM 'users' WHERE 'username' = '. $_POST['username'];is just ASKING for a SQL Injection. I suggest you use PHP Data objects - http://php.net/manual/en/book.pdo.php.

在继续之前,SELECT * FROM 'users' WHERE 'username' = '. $_POST['username'];只是请求 SQL 注入。我建议您使用 PHP 数据对象 - http://php.net/manual/en/book.pdo.php

So as I understood I must pass the POST values via $.ajax too, correct? If yes, how I will be able to access them via validation.php file?

所以据我所知,我也必须通过 $.ajax 传递 POST 值,对吗?如果是,我将如何通过validation.php 文件访问它们?

Because this is a simple request, I suggest you use JQuery's method $.post(). Here's a sample based off of what you're trying to do.

因为这是一个简单的请求,我建议你使用 JQuery 的方法$.post()。这是基于您尝试执行的操作的示例。

$.post('validation.php',{username: $('#username').val()}, function(data){
    if(data.exists){
        //tell user that the username already exists
    }else{
        //username doesn't exist, do what you need to do
    }
 }, 'JSON');

jQuery's post method takes 4 parameters $.post(url, data, callback, datatype). In the example above, we will be posting the username with $('#username').val()to validation.phpand expect a JSONresponse. When the request is finished, the callback function will be executed with databeing the response from the request. Because we specified that that response will be JSON, we can access it just like a native object in javascript. Now let's move to validation.php

jQuery 的 post 方法需要 4 个参数$.post(url, data, callback, datatype)。在上面的示例中,我们将使用$('#username').val()to发布用户名validation.php并期待JSON响应。当请求完成时,回调函数将作为data请求的响应执行。因为我们指定该响应将是JSON,所以我们可以像访问 javascript 中的本机对象一样访问它。现在让我们转到validation.php

Like I stated above, I suggested you use PDO for your database driver. So in this example, I will show you a basic usage of it.

就像我上面所说的那样,我建议您将 PDO 用于您的数据库驱动程序。所以在这个例子中,我将向你展示它的基本用法。

//set the headers to be a json string
header('content-type: text/json');

//no need to continue if there is no value in the POST username
if(!isset($_POST['username']))
    exit;

//initialize our PDO class. You will need to replace your database credentials respectively
$db = new PDO('mysql:host=DATABASE_HOST;dbname=DATABASE_NAME','DATABASE_USERNAME','DATABASE_PASSWORD',array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));

//prepare our query.
$query = $db->prepare('SELECT * FROM users WHERE username = :name');
//let PDO bind the username into the query, and prevent any SQL injection attempts.
$query->bindParam(':name', $_POST['username']);
//execute the query
$query->execute();

//return the json object containing the result of if the username exists or not. The $.post in our jquery will access it.
echo json_encode(array('exists' => $query->rowCount() > 0));

Now to recap, our jQuery script will post to validation.phpwhere it selects a username from the database. It will return a JSONobject that has a key of existsthat is a boolean indicating if the username already exists as a row in your database. When the request is complete via jQuery, you can do what you need based off the result of the query. I hope this is a thorough explanation and leads you to what you are hoping to accomplish.

现在回顾一下,我们的 jQuery 脚本将发布到validation.php它从数据库中选择用户名的位置。它将返回一个JSON对象,该对象的键exists是一个布尔值,指示用户名是否已作为数据库中的一行存在。当请求通过 jQuery 完成后,您可以根据查询结果执行所需的操作。我希望这是一个彻底的解释,并引导您完成您希望完成的工作。

回答by Bhawk1990

With reading tutorials on the internet, you can learn lots of things. I recommend you to follow the instructions on the following page: http://blog.webwizo.com/2011/05/04/simple-login-with-php-and-jquery-ajax/

通过阅读互联网上的教程,您可以学到很多东西。我建议您按照以下页面上的说明进行操作:http: //blog.webwizo.com/2011/05/04/simple-login-with-php-and-jquery-ajax/

You send the username via post to the specified php file, which searches for the username you have provided.

您通过 post 将用户名发送到指定的 php 文件,该文件会搜索您提供的用户名。

Please, use the mysql_real_escape_string function on the input string, so hackers will not be able to use a sql injection attack on your website. It works like this:

请在输入字符串上使用 mysql_real_escape_string 函数,这样黑客将无法在您的网站上使用 sql 注入攻击。它是这样工作的:

$query = "SELECT * FROM users WHERE username = '".mysql_real_escape_string($_POST['username'])."'";
if (mysql_num_rows(mysql_query($query)) > 1)
{ 
    print "inuse";
} 

Then you can check the response value in your ajax jquery function. If the website returns the value "inuse", show an error message that the username is already in use. If not, the username is available.

然后你可以在你的 ajax jquery 函数中检查响应值。如果网站返回值“inuse”,则显示用户名已被使用的错误消息。如果没有,则用户名可用。

But as I've said, please check the tutorial and the most important thing: Use mysql_real_escape_string to prevent sql injection attacks

但正如我所说,请查看教程和最重要的事情: 使用 mysql_real_escape_string 来防止 sql 注入攻击

回答by romainberger

Here is what I did on one of my website: on validation.php I count the number of member with the username then here is the jquery script:

这是我在我的一个网站上所做的:在validation.php上,我用用户名计算成员的数量,然后这里是jquery脚本:

var username = $('#username').val();
$('#username').change(function() {
   $.ajax({
      url: "validation.php",
      type: 'POST',
      data: 'username=' + username,
      success: function(result){
                 if(result > 0){
                     // do something if username already exist
                 }
                 else{
                     // do something if username doesn't exist
                 }
               }
      });
});

回答by Mindaugas Jakubauskas

  1. if (mysql_num_rows(mysql_query("SELECT * FROM users WHERE username='".$_POST['username']."'")) < 1) { 
        true; 
    } else { 
        false; 
    }
    
  2. you can pass it by get or post methods. in validation.php you just have to write $somevar=$_POST['somevar'];

  3. as I just said you cant pass variables by post or get methods - to do this task, you mustus GET.

  1. if (mysql_num_rows(mysql_query("SELECT * FROM users WHERE username='".$_POST['username']."'")) < 1) { 
        true; 
    } else { 
        false; 
    }
    
  2. 您可以通过 get 或 post 方法传递它。在validation.php中你只需要写$somevar=$_POST['somevar'];

  3. 正如我刚才所说,您不能通过 post 或 get 方法传递变量 - 要完成此任务,您必须使用GET。

i hope i was helpful ;)

我希望我有帮助;)