Ajax No Refresh Verification registration information Sample _ajax related

Source: Internet
Author: User
Tags error code eval php file urlencode strong password

Ajax No Refresh Verification Registration information sample, the approximate idea is as follows:
I. To do the registered HTML page (HTML+CSS)
1. Do not need form form, directly with Div wrapped
2. Four labels are required to display the correct and wrong information
3. Without submit button, use button directly

As shown in figure:

Two. Ajax into a function, by passing simple parameters can be exchanged with the server data.

1. This Ajax function is described in detail in the previous article on how to handle the return data using AJAX processing.
The 2.ajax function requires three parameters, url,jsondata,getmsg. The URL here is regprocess.php,jsondata to upload the data that the server validates, getmsg is the function to get the returned data.
3. Repeat the 2nd step to verify that four information is completed

Three. Do a regprocess.php file to process the registration information

1. This is to deal with the data from Ajax, pay attention to send the way is post so receive the way is also post
2. The data are received after the verification, is to judge. The most important thing is whether you can receive the data successfully, you must not receive the wrong data.
Notice here that there are some special characters that are not displayed correctly when they are uploaded to the server, for example ' + ' will be shown as ' spaces ', For more information, please search by yourself. So when the server receives a special character, it needs to be coded before it can be used correctly. PHP uses the UrlEncode function to encode the URL.

Four. Write functions that need to be used, put them in another myfunc.php file, and import them directly into the regprocess.php file.

1. Verify that the user name is illegal and is registered
2. Verify the password is illegal, how much strength
3. Verify that the password is entered consistently
4. Verify that the mailbox is illegal, whether it has been registered
5. Save user information to database
Then, in regprocess.php, use these functions to directly process the returned error code.

Five. Return the processed data, here I return as a string of JSON, and then JS again to parse.

1. The returned data is to be spliced into JSON format.
JSON format: {name1:value1,name2:value2};
But what we are going to return is actually a string, so it should be ' {name1 ': ' value1 ', ' name2 ': ' value2 '} ';
2. After returning to the front end, use the Eval function of JS to parse into a JSON object.
For example: var json = eval (' (' +oajax.responsetext+ ') ');
3. Verify the information displayed in the corresponding input after.
4. Click to register, submit all the data at once, if there is no mistake, keep the registered user information, and prompt registration success.

The successful registration effect is as follows:


The database also updated the information just registered


The registration failure effect is shown below:


Here's the main code:

HTML code

<div id= "Reg" >
  <label> User name: <input type= "text" id= "username"/></label><label>< /label><br/><br/>
  <label> Password: <input type= "password" id= "PASSW"/></label>< br/><br/>
  <label> Confirm password: <input type= "password" id= "REPASSW"/></label><br/> <br/>
  <label> Email: <input type= "text" id= "email"
  /></label><br/><br <button id= "BTN" > Registration </button>
  <span id= "user" ></span>
  <span id= "Pass" ></ span>
  <span id= "rep" ></span>
  <span id= "em" ></span>
 </div>


CSS Code

#reg {width:400px;height:300px;position:relative;margin:10px Auto}
  #reg label{float:right;position:relative; margin-top:10px;font-size:28px;}
  #reg label input{width:250px;height:40px;font-size:24px;}
  #reg #btn {width:120px;height:40px;position:absolute;right:65px;margin-top:80px;}
  #reg span{width:200px;position:absolute;right: -210px;font-size:24px;}
  #reg #user {top:20px;}
  #reg #pass {top:75px;}
  #reg #rep {top:130px;}
  #reg #em {top:185px;}
  . error{color:red}
  . Ok{color:greenyellow;}

JS Code

 <script src= ". /.. /..
   /ajax.js "></script> <script> window.onload = function () {//Background verification bgprocess (); Submit the registration information, return the registration success or not $ (' btn '). onclick = function () {var jsondata = {username:$ (' username '). value,passw:$ (' PASSW ')
    . Value, repassw:$ (' REPASSW '). value,email:$ (' email '). Value};
   Ajax (' regproccess.php ', Jsondata,getinfo, ' json ');
   };
    function GetInfo (info) {var a = [' username ', ' passw ', ' repassw ', ' email '];
    var b = [' User ', ' pass ', ' rep ', ' em '];
    var flag = true;
      for (var i =0;i<info.length;i++) {if (Info[i].state = = ' false ') {flag = false; DisplayInfo (Info[i],b[i],a[i]);
   Display error message} if (flag) alert (' Congratulations on your Registration success ');
  }
  }; Background validation function bgprocess () {//Verify user name $ (' username '). onblur = function () {var jsondata = {Username:this.
    Value};
   Ajax (' regproccess.php ', Jsondata,getuser, ' json ');
   };
   function GetUser (msg) {DisplayInfo (msg[0], ' user ', ' username ');
}   Verify password $ (' PASSW '). onkeyup = $ (' PASSW '). Onblur= function () {var jsondata = {Passw:this.value};
   Ajax (' regproccess.php ', Jsondata,getpass, ' json ');
   };
   function Getpass (msg) {DisplayInfo (msg[1], ' Pass ', ' PASSW ');
    //Confirm Password $ (' REPASSW '). onblur = function () {var jsondata = {passw:$ (' PASSW '). Value,repassw:this.value};
   Ajax (' regproccess.php ', Jsondata,getrepass, ' json ');
   };
   function Getrepass (msg) {DisplayInfo (msg[2], ' rep ', ' REPASSW ');
    //Verify Mailbox $ (' email '). Onblur= function () {var jsondata = {Email:this.value};
   Ajax (' regproccess.php ', Jsondata,getemail, ' json ');
   };
   function Getemail (msg) {DisplayInfo (msg[3], ' em ', ' email '); }//Display information function DisplayInfo (msg,id,name) {$ (id). ClassName = (Msg.state = = ' true ')? '
   Ok ': ' Error ';
  $ (id). InnerHTML = Msg[name];
  function $ (ID) {return document.getElementById (ID); } </script>

myfunc.php Code:

<?php/** * @function Verify username * @param $username username * @return Returns a $res array containing the error code, 1: User name is illegal, 1: No user name, 1: Username exists * * Fun
 Ction Verifyuser ($username) {$res = array ();
 Match successfully returns the number of matches, 0 means no match, matching letters, numbers, underscores if (Preg_match ("/^\\w{6,16}$/", $username) = = 0) $res [] = 1;
 else $res [] = 0;
 if (empty ($username)) $res [] = 1;
 else $res [] = 0;
 if (Verifydata ($username, ' username '))//Verify that the username is registered $res [] = 1;
 else $res [] = 0;
return $res; /** * @function Verify password is illegal and password strength * @param $passw password * @return $res password strength/function VERIFYPASSW ($PASSW) {$reg 1 = '/ ^[0-9]{8,16}$/'; Pure digit $reg 2 = '/^[a-za-z]{8,16}$/';//pure letter $reg 3 = '/^[a-za-z\+]{8,16}$/';//Pure letter + $reg 4 = '/^[0-9a-za-z]{8,16}$/';//number and letter Group
 $reg 5 = '/^[0-9a-za-z\+]{8,16}$/';//number, ' + ' and letter combination $res;
 if (empty ($PASSW)) $res =-1;
 else if (Preg_match ($reg 1, $PASSW)) $res = 1;
 else if (Preg_match ($reg 2, $PASSW)) $res = 1;
 else if (Preg_match ($reg 3, $PASSW)) $res = 2;
 else if (Preg_match ($reg 4, $PASSW)) $res = 2; else if (Preg_match ($reG5, $PASSW)) $res = 3; else $res = 0;
illegal password return $res; /** * @function Verify that the mailbox is illegal and has been registered for use * @param $email mailbox * @return $res error code/function Verifyemail ($email) {$reg = '/^ ([\w-*\.*]) +@ (\w-?)
 + (\.\w{2,}) +$/';
 $res;
 if (empty ($email)) $res =-1;
 else if (Verifydata ($email, ' mailbox ')) $res = 1;
 else if (Preg_match ($reg, $email)) $res = 2; else $res = 0;
Illegal mailbox return $res; /** * @function Verify that data already exists * @param $data * @param $query * @return data exists to return 1, otherwise it returns 0 */function Verifydata ($data
 , $query) {//1. Connection database @ $db = new mysqli (' localhost ', ' root ', ' root ', ' user_passd ');
 if (Mysqli_connect_errno ()) Die ("Connection Database Failed");
 2. Verify that the data exists $sql = "Select $query from login where $query = ' {$data} '";
 $res = $db->query ($sql);
 $row = $res->fetch_assoc ();
 3. Close the database $db->close ();
Return Is_null ($row)? 0:1; /** * @function Save registered User information * @param $data the data to be saved, an array * @return bool $res return True to indicate that the information was saved successfully, false indicates failure/function Savere Ginfo ($data) {//1. Connection database @ $db = new MySqli (' localhost ', ' root ', ' root ', ' user_passd ');
 if (Mysqli_connect_errno ()) Die ("Connection Database Failed");
 2. Insert Data $sql = "INSERT into login values (' {$data [0]} ', ' {$data [1]} ', ' {$data [2]} ')";
 $res = $db->query ($sql);
 3. Close the database $db->close ();
return $res;

 }

Regprocess.php Code

<?php header ("Content-type:text/html;charset=utf-8");
Disabling caching is a normal submission for data, rather than caching the data header ("Cache-control:no-cache"); Include (' myfunc.php '); Contains my library $username = isset ($_post[' username '])? $_post[' username ']: ';  Get username $passw =isset ($_post[' PASSW '])? UrlEncode ($_post[' PASSW ']): '; Get Password $REPASSW = isset ($_post[' REPASSW '])? UrlEncode ($_post[' REPASSW ']): '; Get confirmation Password $email = isset ($_post[' email ')]? $_post[' email ': ';   Get Mailbox $info = ' ['; The data that holds the return page $isSucceed = 0;
Determine if the registration is successful, if the final result is 4, it means that all correct, registered successfully//1. Verify that the username is illegal $res 1 = verifyuser ($username);
if ($res 1[1]) $info. = ' {username ': "Please enter user name", "state": "false"} ';
else if ($res 1[0]) $info. = ' {username ': ' username illegal ', ' state ': ' false '} ';
else if ($res 1[2]) $info. = ' {username ': ' User name already exists ', ' state ': ' false '} ';
 else {$info. = ' {' username ': ' User name available ', ' state ': ' true '} ';
+ + $isSucceed;
$info. = ', ';
2. Verify password is illegal and strength $res 2 = VERIFYPASSW ($PASSW);
if ($res 2 = = 1) $info. = ' {PASSW ': "Please enter password", "state": "false"} '; else if ($res 2 = = 0) $info. = ' {passw ': ' Password illegal ', ' state ': ' false '}';
 else {if ($res 2 = = 1) $info. = ' {PASSW ': ' Weak password strength ', ' state ': ' true '} ';
 else if ($res 2 = = 2) $info. = ' {passw ': ' Password intensity is medium ', ' state ': ' true '} ';
 else if ($res 2 = = 3) $info. = ' {PASSW ': ' Strong password ', ' state ': ' true '} ';
+ + $isSucceed;

$info. = ', ';
3. Confirm Password if (empty ($REPASSW)) $info. = ' {REPASSW ': "Please enter password First", "state": "false"} ';
 else if ($PASSW = = $REPASSW) {$info. = ' {' REPASSW ': ' Password consistent ', ' state ': ' true '} ';
+ + $isSucceed;
else $info. = ' {' REPASSW ': ' Inconsistent password ', ' state ': ' false '} ';

$info. = ', ';
4. Verify mailbox $res 3 = Verifyemail ($email);
if ($res 3 = = 1) $info. = ' {email ': "Please enter the mailbox", "state": "false"} ';
else if ($res 3 = 0) $info. = ' {email ': ' Mailbox illegal ', ' state ': ' false '} ';
else if ($res 3 = 1) $info. = ' {email ': "This mailbox has been registered", "state": "false"} ';
 else if ($res 3 = = 2) {$info. = ' {email ': ' This mailbox is available ', ' state ': ' true '} ';
+ + $isSucceed;
///Save user registration information if ($isSucceed = = 4) savereginfo (Array ($username, $PASSW, $email));

 echo $info. = '] ';

Although this example is simple, but still can let the novice probably understand how the front-end is to pass the data to the back end, and how to return the data to the front end.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.