jquery Ajax user authentication and Registration Technology example tutorial (with demo source) _jquery

Source: Internet
Author: User
Tags md5 jquery library

This paper introduces the Jquery+ajax registration real-time authentication and the method of using jquery to $.ajax for instant verification. This further summarizes the AJAX user authentication and registration techniques for jquery. Share to everyone for your reference, specific as follows:

Ajax form submission is a powerful technology that provides a way to send Web Forms without overloading the browser window. The JQuery library lets you use the Ajax form submission feature to further provide a quick and easy way to generate AJAX-enabled WEB forms in small amounts of code. In this article, learn how to use JQuery to create a basic Ajax form submission, and how to use that technology to authenticate a user. This article uses JQuery to demonstrate Ajax user registration techniques, such as checking user name availability and prompting the user name when the selected username already exists. Neither form submission nor page overload is required.

If you are not very familiar with jQuery, it is essentially a JavaScript library, making JavaScript development easy. It minimizes the amount of code required because it has many built-in features so that you no longer need to write client functions or objects for these features. For more information and links to the jquery library, see the information on this site, or, as you can see in all code samples, embed the current version of the jquery library directly.

Use JQuery for form submission

Submitting a form without overloading can be useful in many scenarios. For example, with it, you can use JavaScript code to validate form fields before submitting a form, or to submit a form in a single page application or-as this article shows-to determine if the user name has already been registered. There are two ways to use jQuery to trigger a form submission: Use the submit handler function or the click handler function. Listing 1 shows how to submit a form using the submit handler function.

Listing 1. Submitting a form using the submit processing function of JQuery

<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 function

<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>

The two listings are basically the same: they are embedded in the JQuery library, using the Ready handler function to confirm that the page is loaded before accessing any element, and the handler function includes the same code. The only difference is the processing function and the elements assigned to the processing function. The submit handler function needs to assign a form element, and the click handler function, any clickable element, is the submit button in this example. 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 a parameter) or use it to access the function.

Although both of these options are valid, the submit processing function is more commonly used. In some cases, however, you may have more than one Submit button, which requires a click handler for each button. Listing 3 shows a scenario in which the click handler function must be used because the two submit buttons can touch the publication form submission.

Listing 3. Submit the 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> <div id=" container "> <div id=" message "></div> <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 "/>  

Note that in this example, the form can perform multiple activities: an existing user can log in, and a new user can register by entering additional account information. Use the submit handler function on the form to not run in this scenario because it cannot determine which button touches the publish order submission. Therefore, listing 4 uses the click handler function to determine what action each button takes to make it easier for you to work with the data later.

Listing 4. The Click handler function for the 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 ();
 });


When the document is ready, you need to assign the click handler function for the Register and Login buttons. The click handler function receives an argument named E (as an event). This event object is later used to prevent default form submissions. As described in the previous code. When the click handler function is invoked, 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 use jquery to submit a form, let's take a look at how Ajax is used in jquery and how PHP authenticates a user.

Use Ajax features in JQuery to register and authenticate a user

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, and you do not need to use any particular server-side language or database to create this function.

Start by writing additional code in the JavaScript file and using Ajax to send the form to PHP. The code in Listing 5 starts as well as listing 4 because it contains the ready and click Handlers for the button, and it determines which button to click. Then, if the message element is open, you need to use the Slideup function to close it. The AJAX call is not obvious, especially if you used to not use JQuery to create Ajax, because you usually use the shorthand function to send the call without even mentioning Ajax in the code.

Listing 5. Use Ajax in JQuery to submit a Web Form

 $ (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 co
  De = $ (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 ();
});

}); 

The post function is a shorthand function, which is equivalent to the code in Listing 6. It points the file path to the requested file, serializes the data, and finally a callback function. It's easy to serialize form data in JQuery: You just need to access the form element and invoke the Serialize feature to get a standard query string. The callback function first determines whether the call succeeded or failed by accessing the first node of the response: the PHP file returns the result with a node named success or error. After the status is determined, you can remove any of the classes left in the message element from the previous form submission. Then add a class that responds to the success. Message elements are appended to the HTML that declares success or error messages, and then use the Slidedown function of JQuery to open it.

Listing 6. JQuery Ajax functions

$.ajax ({
 type: ' POST ',
 url:url,
 data:data,
 success:success
 datatype:datatype
});

Before you create a PHP file that interacts with a database, you need to build a database that you plan to save new users and select existing user forms. Listing 7 contains the SQL code you need to create a MySQL table named Ibm_user_auth, which includes an ID, username, password, first name, last name, and Email address. The ID is set to AutoIncrement and as the primary key. Other values are tinytext, except for the password, which is varchar (32), because you will use it later to save a value for message digest algorithm 5 (MD5) encryption.

Listing 7. SQL code to create a MySQL database table for users

CREATE TABLE ' Ibm_user_auth ' (
 ' id ' int () NOT NULL auto_increment,
 ' username ' tinytext not null,
 ' password ' varchar ' isn't null,
 ' firstname ' tinytext not NULL,
 ' lastname ' tinytext not NULL,
 ' email ' tinytext NOT NULL ,
 PRIMARY KEY (' id ')
);

Once the table is built, you can start writing PHP code that interacts with the database. You will invoke the file in your Ajax post function named service.php. Listing 8 shows the code that makes up the file. First, define the database connection variables. After the database information is established, make sure that the username and password are posted through the form and, if so, extract the posted data and connect to the database. Now that you have connected to the database, you need to determine whether to use the Send data to log in to an existing user or register him/her as a new user. You just need to check that the action variables are extracted from the posted data and posted by an Ajax form, and you can be sure.

If you are sure that this is a new user registration, you also need to make sure that the name, last name, and email address have been sent. Otherwise, it can only be an error, and when all the requirements are met, make sure that the user name does not duplicate the existing username in the database, and if it is repeated, it returns an error. Otherwise, continue verifying the email address, inserting the new user database into the database, and then returning a success message.

If you are sure that this is a login that an existing user wants, make sure that the username is in the database. If so, save the user data to a session, and then return a success message.

Listing 8. Server-side PHP code that interacts with JAVASCRIPT code and database

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 a 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 '/>");

 }}?>

Now that you've done the important work, it might be a good idea to consider using performance. The biggest problem with this code is that you can't tell the user what the error is if an error occurs. However, you may notice that each error response contains an id attribute, and the next section shows you how to use these values to write an error response for each scenario, and to prompt the user name during registration.

Handling errors and prompting user names during registration

At this point, it is easier to use the code above to handle errors. In particular, you have returned an error, and the error contains a specific ID pointing to the problem that may have occurred. If you have already built the ID, start adding PHP code that prompts the user name before returning to the JavaScript code. Listing 9 provides an example of how a user name can be created based on user submission information-the first and last name in this example.

Listing 9. Create a user name hint using submitted user data

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 a 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 '/>");

 }}?>

Note that if the user name already exists during the registration process, you can create an XML structure that contains the various submission user name combination data (which forms the prompt user name). You can even further confirm that the user name hint is not in the database before returning.

Use JQuery to display tips

Listing 10. Use JQuery to display prompt user name

$ (document). Ready (function () {$ (#register, #login). Click (function (e) {var name = ($ (event.target). attr (' id ') = = ' re Gister ')?
 ' 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 your entered was invalid. ');
  Break
  Default: $ (' #message '). HTML (' An error occurred, please try again. ')
 } $ (' #message '). Slidedown (' fast ');
 });
 return E.preventdefault ();
});

 });

Now, if you return an error, you can check the error ID, not just the default error message that does not help the user. First, the ID is parsed from the XML structure (returned from PHP), and then a conversion statement is used to point directly to the message or related code. The first error ID is used in cases where a user name already exists in the system. This is where you access the prompt user name and show the user a selection of new user names. Starts at the Access prompt node and traverses each node. During traversal, create a radio button and a label that contains a hint, and then attach it to the error message to display to the user. At this point, the user can select a hint name that will automatically be added to the User Name text box and then continue to register.

The next error ID is for email address verification. The related code displays only a common error message informing the user of what went wrong. You can even add a line of code to highlight an incorrect field. The next is a common error message that is used when a login fails. In this case, the code uses a rather vague message that, for security reasons, you can't tell anyone that the field is incorrect. Finally, the default message is the same as in your listing 5, and the message may never be used, but it is a good precaution.

Conclusion

The growing popularity of using Ajax for user authentication is almost essential for a single page application. It is also good for prompting the user name, as described in this article, because when the page is submitted, it gives the user a false hope that it will only refresh if there is an error, which means that the response is more automated and user-friendly. It also provides a better web experience.

Full instance code click here to download the site.

I hope this article will help you with the jquery program design.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.