Home > Article > Web Front-end > Detailed explanation of Ajax user authentication and registration
This time I will bring you a detailed explanation of the use of Ajax user authentication and registration. What are the precautions for Ajax user authentication and registration? The following is a practical case, let's take a look.
Ajax form submission is a powerful technology that provides a way to send web forms without reloading the browser window. The jQuery library lets you use Ajax form submission capabilities to further provide a convenient and fast way to generate Ajax-enabled Web forms with a small amount of code. In this article, learn how to create a basic Ajax form submission using jQuery, and how to authenticate a user using this technique. This article demonstrates Ajax user registration techniques using jQuery, such as checking username availability and prompting for a username when the selected username already exists. Neither form submission nor page reload is required. If you’re not very familiar with jQuery, it’s essentially a JavaScript library that makes JavaScript development easy. It minimizes the amount of code required because it has many built-in functions so that you no longer need to write client functions or objects for these functions. More information and links to download the jQuery library can be found on this site; alternatively, as you can see in all code samples, you can embed the current version of the jQuery library directly.Using jQuery for form submission
Being able to submit a form without reloading is useful in many scenarios. With it, you can, for example, use JavaScript code to validate form fields before submitting the form in a single-page application or—as shown in this article—to determine whether a username has already been registered. There are two ways to trigger a form submission using jQuery: using the submit handler or the click handler. Listing 1 shows how to submit a form using the submit handler.List 1. Submit the form using jQuery's submit handler function
<script type="text/javascript" src="http://code.jquery.com/jquery.js"></script> <script type="text/javascript"> $(document).ready(function() { $('#submitForm').submit(function(e) { alert($('#sample').attr('value')); return e.preventDefault(); }); }); </script> <form id="submitForm" method="post"> <input type="text" name="sample" id="sample" value="Enter something" /> <input type="submit" id="submitBtn" value="Submit" /> </form>
Submit the form using the click handler function:
Listing 2. Submitting a form using jQuery's click handler
<script type="text/javascript" src="http://code.jquery.com/jquery.js"></script> <script type="text/javascript"> $(document).ready(function() { $('#submitBtn').click(function(e) { alert($('#sample').attr('value')); return e.preventDefault(); }); }); </script> <form id="submitForm" method="post"> <input type="text" name="sample" id="sample" value="Enter something" /> <input type="submit" id="submitBtn" value="Submit" /> </form>These two lists are basically the same: they both embed the jQuery library and use the ready handler before accessing any element Confirm that the page is loaded and the handler function includes the same code. The only difference is the handler function and the elements assigned to the handler function. The submit handler needs to be assigned a form element, while the click handler needs to be assigned to any clickable element — in this case, the Submit button. To avoid refreshing the page when submitting the form, you must use the preventDefault function. To access the preventDefault function, you must pass the handler function (even as an argument) or use it to access the function. Although both of the above options are valid, the submit processing function is more commonly used. However, in some cases, you may have more than one Submit button, which requires a click handler for each button. Listing 3 shows a scenario where a click handler is necessary because both Submit buttons trigger form submission.
Listing 3. Submitting a form using two submit buttons
<script type="text/javascript" src="http://code.jquery.com/jquery.js"></script> <script type="text/javascript" src="register.js"></script> <p id="container"> <p id="message"></p> <form method="post" id="mainform"> <label for="username">Username</label> <input type="text" name="username" id="username" value="" /> <label for="password">Password</label> <input type="password" name="password" value="" /> <input type="submit" name="action" id="login" value="Log in" /> <h2>Extra options (registration only)</h2> <label for="firstname">First name</label> <input type="text" name="firstname" value="" /> <label for="lastname">Last name</label> <input type="text" name="lastname" value="" /> <label for="email">Email</label> <input type="text" name="email" value="" /> <input type="submit" name="action" id="register" value="Register" /> </form> </p>Note that in this example this form can perform multiple activities: existing users can log in, new Users can register by entering additional account information. Using the submit handler on the form won't work in this scenario because it can't determine which button triggered the form submission. Therefore, Listing 4 uses a click handler function to determine what action each button takes so that you can later process the data.
Listing 4. Click handler function for submit button in register.js
$(document).ready(function() { $("#register, #login").click(function(e) { var name = ($(event.target).attr('id') == 'register') ? 'Registration' : 'Login'; return e.preventDefault(); }); });After the document is ready, you need to assign click handler functions to the Register and Login buttons. The click handler function receives a parameter named e (as the event). This event object is later used to prevent default form submission. As stated in the previous code. When the click handler is called, the ID of the currently clicked object is accessed to determine whether this is a
user login or a new user registration.
Now that you know how to submit a form using jQuery, let’s take a look at how to authenticate a user using Ajax and PHP in jQuery.Registering and authenticating a user using Ajax functionality in jQuery
To authenticate and register a user, you need a server-side language and a database. In this article, the server-side language is PHP and the database is MySQL. You don't need to use any specific server-side language or database to create this function.首先开始在 JavaScript 文件中编写附加代码,使用 Ajax 将表单发送给 PHP 。清单 5 的代码开始也类似于清单 4 ,因为它包含按钮的 ready 处理函数和 click 处理函数,而且它确定点击哪个按钮。然后,如果消息元素是打开的,您需要使用 slideUp 函数关闭它的。咋一看 Ajax 调用不是很明显,特别是如果您过去通常不 使用 jQuery 创建 Ajax,因为您通常使用简写函数来发送调用,在代码中甚至都没提及 Ajax。
清单 5. 使用 jQuery 中的 Ajax 提交一个 web 表单
$(document).ready(function() { $("#register, #login").click(function(e) { var name = ($(event.target).attr('id') == 'register') ? 'Registration' : 'Login'; $('#message').slideUp('fast'); $.post('service.php', $('#mainform').serialize() +'&action='+ $(event.target).attr('id'), function(data) { var code = $(data)[0].nodeName.toLowerCase(); $('#message').removeClass('error'); $('#message').removeClass('success'); $('#message').addClass(code); if(code == 'success') { $('#message').html(name + ' was successful.'); } else if(code == 'error') { $('#message').html('An error occurred, please try again.'); } $('#message').slideDown('fast'); }); return e.preventDefault(); }); });
post 函数是一个简写函数,等价于清单 6 中的代码。它将文件路径指向被请求的文件、序列化数据、最后是一个回调函数。用 jQuery 序列化表单数据比较容易:您只需要访问 form 元素和调用 serialize 功能获取一个标准查询字符串。回调函数首先通过访问响应的第一个节点来确定调用是成功还是失败:PHP 文件以一个名为 success or error 的节点返回结果。状态确定之后,您就可以从之前的表单提交中删除 message 元素中留下的任何类。然后添加一个响应成功对应的类。message 元素被附加到声明成功或错误消息的 HTML 后,然后使用 jQuery 的 slideDown 函数打开 message。
清单 6. jQuery Ajax 函数
$.ajax({ type: 'POST', url: url, data: data, success: success dataType: dataType });
在创建同数据库交互的 PHP 文件之前,您需要构建您计划保存新用户和选择现有用户表单的数据库。清单 7 包含了您需要的 SQL 代码,来创建名为 ibm_user_auth 的 MySQL 表,其中包括一个 ID,用户名、密码、名字、姓、以及 Email 地址。ID 被设置为自动增量并作为主键。其他值都是 tinytext 型的,除了密码,密码是 varchar(32) 的,因为稍后您将使用它来保存一个消息摘要算法 5(MD5)加密的值。
清单 7. 为用户创建 MySQL 数据库表的 SQL 代码
CREATE TABLE `ibm_user_auth` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` tinytext NOT NULL, `password` varchar(32) NOT NULL, `firstname` tinytext NOT NULL, `lastname` tinytext NOT NULL, `email` tinytext NOT NULL, PRIMARY KEY (`id`) );
表构建完成之后,您就可以开始编写与数据库交互的 PHP 代码了。您将在您的 Ajax post 函数中调用该文件 — 名为 service.php。清单 8 显示了构成该文件的代码。首先定义数据库连接变量。数据库信息建立之后,确保用户名和密码被通过表单张贴传递;如果是这样,提取张贴数据然后连接到数据库。现在您已经连接到数据库了,需要确定是否使用发送数据来登录一个已有用户或注册他/她作为一个新用户。您只需要检查 action 变量是从张贴数据提取的和被 Ajax 表单张贴发送的,就可以确定了。
如果您确定这是一个新用户注册,您也需要确定名字、姓和 email 地址已经发送。否则,只能是一个错误,当所有需求都满足之后,确保用户名不和数据库中现有的用户名重复,如果是重复了,也是返回一个错误。否则,继续验证 email 地址,将新用户数据库插入数据库,然后返回一个成功消息。
如果您确定这是一个现有用户想要的登录,确保用户名是存在数据库中。如果是,将用户数据保存到一个会话中,然后返回一个成功消息。
清单 8. 与 JavaScript 代码和数据库交互的服务器端 PHP 代码
// Database connection values define('DB_HOST', 'localhost'); define('DB_USERNAME', 'YOUR_USERNAME'); define('DB_PASSWORD', 'YOUR_PASSWORD'); define('DB_NAME', 'YOUR_DB_NAME'); if(isset($_POST['username'], $_POST['password'])) { extract($_POST); $db = mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD); mysql_select_db(DB_NAME, $db); if($action == 'register' && isset($_POST['firstname'], $_POST['lastname'], $_POST['email'])) { // Verify that the username is unique $query = mysql_query("select count(id) from ibm_user_auth where username='$username'"); $result = mysql_fetch_row($query); if ( $result[0] > 0 ) { die("<error id='0' />"); } // Validate email if( !preg_match("^[a-z0-9,!#\$%&'\*\+/=\?\^_`\{\|}~-]+(\.[a-z0-9,!#\$%& '\*\+/=\?\^_`\{\|}~-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*\.([a-z]{2,})$^", $_POST['email']) ) { die("<error id='1' />"); } mysql_query("insert into ibm_user_auth (username, password, firstname, lastname, email) VALUES ('$username', MD5('$password'), '$firstname', '$lastname', '$email')"); die("<success />"); } else if($action == 'login') { $query = mysql_query("select count(id) from ibm_user_auth where username='$username' and password=md5('$password')"); $result = mysql_fetch_row($query); if($result[0] == 1) { session_start(); $_SESSION['username'] = $username; die("<success />"); } else die("<error id='2' />"); } } ?>
现在,您已经完成了要点工作,考虑使用性能可能是一个好主意。该代码最大的问题是如果出现错误不能告知用户是什么错误。然而,您可能注意到了,每个错误响应包含一个 id 属性,下一节向您展示如何使用这些值来为每个场景编写一个错误响应,以及在注册过程中提示用户名。
在注册过程中处理错误和提示用户名
此时,使用上述代码处理错误是较为容易的。特别是您已经返回错误,且错误中含有指向可能出现问题的具体 ID。如果您已经构建了 ID,那么开始添加 PHP 代码,此代码用于在返回到 JavaScript 代码之前提示用户名。清单 9 提供一个如何根据用户提交信息创建用户名暗示的示例 — 本例中是名字和姓。
清单 9. 使用提交的用户数据创建用户名提示
// Database connection values define('DB_HOST', 'localhost'); define('DB_USERNAME', 'YOUR_USERNAME'); define('DB_PASSWORD', 'YOUR_PASSWORD'); define('DB_NAME', 'YOUR_DB_NAME'); if(isset($_POST['username'], $_POST['password'])) { extract($_POST); $db = mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD); mysql_select_db(DB_NAME, $db); if($action == 'register' && isset($_POST['firstname'], $_POST['lastname'], $_POST['email'])) { // Verify that the username is unique $query = mysql_query("select count(id) from ibm_user_auth where username='$username'"); $result = mysql_fetch_row($query); if ( $result[0] > 0 ) { $out = "<error id='0'><suggestions>"; $out .= "<suggestion>" . $firstname . $lastname . "</suggestion>"; $out .= "<suggestion>" . $firstname . "_" . $lastname . "</suggestion>"; $out .= "<suggestion>" . $lastname . $firstname . "</suggestion>"; $out .= "<suggestion>" . $lastname . "_" . $firstname . "</suggestion>"; $out .= "</suggestions></result>"; die($out); } // Validate email if( !preg_match("^[a-z0-9,!#\$%&'\*\+/=\?\^_`\{\|}~-]+(\.[a-z0-9,!#\$%& '\*\+/=\?\^_`\{\|}~-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*\.([a-z]{2,})$^", $_POST['email']) ) { die("<error id='1' />"); } mysql_query("insert into ibm_user_auth (username, password, firstname, lastname, email) VALUES ('$username', MD5('$password'), '$firstname', '$lastname', '$email')"); die("<success />"); } else if($action == 'login') { $query = mysql_query("select count(id) from ibm_user_auth where username='$username' and password=md5('$password')"); $result = mysql_fetch_row($query); if($result[0] == 1) { session_start(); $_SESSION['username'] = $username; die("<success />"); } else die("<error id='2' />"); } } ?>
注意,在注册过程中如果用户名已存在,您可以创建一个包含各种提交用户名组合数据(构成提示用户名)的 XML 结构。您甚至可以进一步在返回之前确认用户名提示不在数据库中。
使用 jQuery 显示提示信息
清单 10. 使用 jQuery 显示提示用户名
$(document).ready(function() { $("#register, #login").click(function(e) { var name = ($(event.target).attr('id') == 'register') ? 'Registration' : 'Login'; $('#message').slideUp('fast'); $.post('service.php', $('#mainform').serialize() +'&action='+ $(event.target).attr('id'), function(data) { var code = $(data)[0].nodeName.toLowerCase(); $('#message').removeClass('error'); $('#message').removeClass('success'); $('#message').addClass(code); if(code == 'success') { $('#message').html(name + ' was successful.'); } else if(code == 'error') { var id = parseInt($(data).attr('id')); switch(id) { case 0: $('#message').html('This user name has already been taken. Try some of these suggestions:'); form = $(document.createElement('form')); $(data).find('suggestions > suggestion').each(function(idx, el) { radio = $(document.createElement('input')); radio.attr({type: 'radio', name: 'suggested', id: 'suggested_'+idx, value: el.innerHTML}); lbl = $(document.createElement('label')); lbl.attr('for', 'suggested_'+idx); lbl.html(el.innerHTML); form.append(radio); form.append(lbl); form.append(''); }); $('#message').append(form); $('#message form input[type="radio"]').click(function() { $('#username').val($(this).attr('value')); }); break; case 1: $('#message').html('The e-mail entered is invalid.'); break; case 2: $('#message').html('The user name or password you entered was invalid.'); break; default: $('#message').html('An error occurred, please try again.'); } } $('#message').slideDown('fast'); }); return e.preventDefault(); }); });
现在,如果返回一个错误,您就可以检查错误 ID,而不只是显示对用户没有帮助的默认错误消息。首先,从 XML 结构(从 PHP 返回的)中解析 ID,然后使用一个转换语句直接指向消息或者相关代码。第一个错误 ID 是用于系统中已经存在一个用户名的情况。这就是您访问提示用户名和为用户展示一个选择新用户名的地方。从访问提示节点开始,遍历每一个节点。遍历过程中创建一个单选按钮和一个包含提示的标签,然后将它附加到错误消息,显示给用户。此时,用户可以选择一个提示名,该名称将自动添加到用户名文本框,然后继续注册。
接下来的错误 ID 是用于 email 地址验证的。相关代码只显示一个常见错误消息,通知用户发生了什么错误。您甚至可以添加一行代码来突出显示不正确的字段。下一个是一个常见错误系消息,用于登录失败时。在本例中,代码使用了一个较为模糊的消息,考虑到安全原因,您不能告诉任何人那个字段是不正确的。最后,默认消息和您 清单 5 中的是一样的,该消息可能永远都不会使用,但是有备无患。
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of Detailed explanation of Ajax user authentication and registration. For more information, please follow other related articles on the PHP Chinese website!