HTML + JS + PHP an original Ajax request example


Today, I’d like to show you the original Ajax request process. Although the Ajax of jQuery is much easier than the original writing method, we should still understand the original writing method. Next, I’ll divide it into three small files: HTML, JS and PHP to show. The database will write by itself.

First, HTML

Copy codeThe code is as follows:
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
< title > a simple ajax request
<script language=”javascript” src=”js/ajaxTest.js”></script>
User name: < input type = “text” > < / input >
Password: < input type = “password” > < / input >
<span style=”color:red;font-weight: bold;”></span><br>
< input type = “button” value = “login” onclick = “showselect()” >

And then JS:

Copy codeThe code is as follows:
*General Ajax complete access process
var xmlHttp

Function showselect() / / click the login button to execute this method
var userName=document.getElementById(“userName”).value;
var passWord=document.getElementById(“passWord”).value;
If (username. Length = = 0) / / verify that the input user name is empty
Document. Getelementbyid (“showinputerror”). InnerHTML = user name cannot be empty// Prompt that the user name cannot be empty
if (xmlHttp==null)
alert (“Browser does not support HTTP Request”)
Var url = “ajaxtest. PHP” / / set the file name of the processing request to submit the action to the background
url=url+”? User name = + user name + “& password = + password / / add the parameter user name and password to the path
Url = URL + “& sid =” + Math. Random() / / add a random number to the path
Xmlhttp. Onreadystatechange = statechanged / / the onreadystatechange event will be triggered whenever the readyState changes. The readyState property contains the state information of XMLHttpRequest
Xmlhttp. Open (“get”, URL, true) / / define the parameters of the request
Xmlhttp. Send (null) / / send request

function stateChanged()
if (xmlHttp.readyState==4 || xmlHttp.readyState==”complete”)//
//0: request not initialized
//1: Server connection established
//2: Request received
//3: Request processing
//4: The request has completed and the response is ready
{ var a= xmlHttp.responseText;// Assign the corresponding data to a
self.location=’Main.php’;// Jump to main.php
Document. Getelementbyid (“showinputerror”). InnerHTML = wrong user name or password// Prompt user name or password error
function GetXmlHttpObject()
var xmlHttp=null;
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
catch (e)
// Internet Explorer
xmlHttp=new ActiveXObject(“Msxml2.XMLHTTP”);
catch (e)
xmlHttp=new ActiveXObject(“Microsoft.XMLHTTP”);
return xmlHttp;

Finally, PHP:

Copy codeThe code is as follows:
$con = mysql_connect(“localhost”,”root”,”123456″);
mysql_select_db(“my_test”, $con);
mysql_query(“set names utf8”);
$sql=”SELECT * FROM Userinfo WHERE userName='”.$userName.”‘ AND pwd='”.$pwd.”‘”;
if ($select>0){$a=”yes”;}
echo $a;