The first AJAX program--php learning Diary II

Source: Internet
Author: User

One, I understand the Ajax

Ajax is a new technology in recent years, mainly using JavaScript technology to implement the user data implicit submission, and allow the program to synchronize or asynchronous processing of data sent by the server. Unlike the traditional "submit" approach, data submission and subsequent processing do not require page switching, providing a good way for users to interact in the browser.
The implementation of Ajax is nothing more than the browser vendors in the browser to provide a public support for AJAX components. This component can have JavaScript calls, submit data to the server side, and receive data sent by the server. After receiving the data, the page can be scripted, displaying the data, which is the result of the server processing the user submitting information in the general sense.
From the point of view above, Ajax and PHP are not directly related to the relationship: Ajax in the client to submit data and receive results; PHP handles data on the server side, but the server-side program is not necessarily PHP, and for Ajax the server side is transparent.

Ii. using AJAX to implement user-defined queries

1, program Description
     just started looking for a tutorial on the internet to learn about Ajax, and also to see a tutorial on Xajax. Xajax is an open source Php&ajax framework that provides a 10-minute tutorial on the home page. But after looking at the found Xajax and PHP tightly combined, inconsistent and I understand Ajax: foreground HTML file, background arbitrary processing script. So the idea of using Xajax to write the first program was abandoned, and an AJAX program was implemented using a simple example framework in the essentials of AJAX development-concepts, cases and frameworks (Kozhong, Electronics Publishers, 2006). But this method is not desirable, because in the following practice there is a problem: The query results are garbled:).
     program functions are the same, users set up the host, connect users, passwords, databases and SQL statements, programs connect to the database, execute SQL statements, and return the results of the query to the user. The procedure constitutes strictly in accordance with previous understandings, consisting of two documents: query.php and form3.html. Where the query.php from the previous code intercept, connect the database, execute the SQL statements, return the query results in tabular form. The form3.html provides a form and submits user data through JavaScript Research AJAX components, receives processing results, and displays the table in <span></span> after receiving results.

2, query.php
Plagiarism before the code
<table width= "80%" border= "1" cellpadding= "0" cellspacing= "1" >
<?php
if (Isset ($_post[' action ')) && $_post[' action ' = = ' submitted ') {//form has been submitted
$link = Mysql_pconnect ($_post[' host '), $_post[' username ', $_post[' password '])
Or Die ("Could not connect:".)  Mysql_error ()); Connect MySQL

mysql_select_db ($_post[' database ')
Or Die ("could not select Database:".) Mysql_error ()); Select Database

$query = $_post[' sql '];
$result = mysql_query ($query)
Or Die ("Query failed:".) Mysql_error ()); Execute a user-submitted SQL statement

 //Header Output Field name
 printf (' <tr> ');
  $numfields = Mysql_num_fields ($result);
 for ($i =0; $i < $numfields; $i + +)//Header
    {echo ' <th> '. Mysql_field_name ($ result, $i). ' </th> ';
    echo "</tr>/n";
   /Output
   while ($row = Mysql_fetch_row ($result)) {
        printf (' <tr> ');
       $cnt = count ($row);
    for ($i =0; $i < $cnt $i + +) {
       if ($row [$i]!= NULL) {
       Echo (' <td> '. $row [$i]. ' </td> ');
   }else{
      Echo (' <td>&nbsp;</td> ');
   }
   }
    printf (' </tr> ');
  }

Mysql_free_result ($result);/release result
Mysql_close ($link);
}
?>
</table>

3, form3.html
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<meta http-equiv= "Content-type" content= "text/html; charset=gb2312 "/>
<title>php&ajax Learning </title>
<script language= "JavaScript" >
//This is the source code provided by the book "Essentials of Ajax development-concepts, cases and frameworks", download address:Http://www.broadview.com.cn/Html/resource/sourcecode.rar
//File: Sourcecode/ajaxch05/ajax_func.js
Code comments are clear enough, but thoroughly understand and read the original book.

var page = "";
Defining XMLHttpRequest Object Instances
var http_request = false;
Defines a reusable HTTP request-sending function
function Send_request (method,url,content,responsetype,callback) {//initialization, specifying handler functions, sending requests
Http_request = false;
Start initializing the XMLHttpRequest object
if (window. XMLHttpRequest) {//mozilla browser
Http_request = new XMLHttpRequest ();
if (http_request.overridemimetype) {//Set MIME category
Http_request.overridemimetype ("Text/xml");
}
}
else if (window. ActiveXObject) {//IE browser
try {
Http_request = new ActiveXObject ("Msxml2.xmlhttp");
catch (e) {
try {
Http_request = new ActiveXObject ("Microsoft.XMLHTTP");
catch (e) {}
}
}
if (!http_request) {//exception, failed to create object instance
Window.alert ("Cannot create XMLHttpRequest object instance.");
return false;
}
if (responsetype.tolowercase () = = "Text") {
Http_request.onreadystatechange = Processtextresponse;
Http_request.onreadystatechange = callback;
}
else if (responsetype.tolowercase () = = "xml") {
Http_request.onreadystatechange = Processxmlresponse;
Http_request.onreadystatechange = callback;
}
else {
Window.alert ("response category parameter error.") ");
return false;
}
Determine how and when to send the request and whether to execute the next code asynchronously
if (method.tolowercase () = = "Get") {
Http_request.open (method, URL, true);
}
else if (method.tolowercase () = = "Post") {
Http_request.open (method, URL, true);
Http_request.setrequestheader ("Content-type", "application/x-www-form-urlencoded");
}
else {
Window.alert ("HTTP request category parameter error.") ");
return false;
}
Http_request.send (content);
}
Functions that handle returning text formatting information
function Processtextresponse () {
if (http_request.readystate = = 4) {//Judge object state
if (Http_request.status = = 200) {//information has been successfully returned to start processing information
res.innerhtml = Http_request.responsetext;//This is the result I have modified, the query data displayed in the <span id= "res" ></span>
} else {//page is not normal
Alert ("The page you are requesting has an exception.) ");
}
}
}
Functions for processing returned XML-formatted documents
function Processxmlresponse () {
if (http_request.readystate = = 4) {//Judge object state
if (Http_request.status = = 200) {//information has been successfully returned to start processing information
Document.writeln (Http_request.responsexml);
Alert ("XML document response.") ");
} else {//page is not normal
Alert ("The page you are requesting has an exception.) ");
}
}
}
</script>
<script language= "JavaScript" >
//Extract the user's data and send it to the database
function query () {
var host,username,password,database,sql
Host = Document.form1.host.value
Username = Document.form1.username.value
Password = Document.form1.password.value
Database = Document.form1.database.value
sql = Document.form1.sql.value
var str;
str = "host=" +host+ "&username=" +username+ "&password=" +password+ "&database=" +database+ "&sql=" +sql + "&action=submitted";
Send_request ("POST", "query.php", str, "text", processtextresponse);
}
</script>
<body>
<center>
<table width= "80%" border= "1" cellpadding= "0" cellspacing= "1" bordercolor= "#000000" >
<caption align= "Left" >
Database Settings
</caption>
<tr>
<td><form id= "Form1" Name= "Form1" "method=" Post "action=" index.php "onsubmit=" This.action.value = ' submitted ' ; return true; Change action Value at commit ">
<p align= "Left" > main &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; machine:
<label>
<input name= "Host" type= "text" value= "localhost"/>
</label>
</p>
<p align= "Left" > &nbsp;&nbsp; user &nbsp; Name:
<label>
<input name= "username" type= "text" value= "root"/>
</label>
</p>
<p align= "left" > Secret &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Code:
<label>
<input name= "password" type= "password" value= "ZP"/>
</label>
</p>
<p align= "Left" > number &nbsp;&nbsp; according to &nbsp; library:
<label>
<input name= "Database" type= "text" value= "Sites"/>
</label>
</p>
<p align= "left" >sql statement:
<label>
<input name= "SQL" type= "text" value= "Show Tables" size= "/>"
</label>
</p>
<center>
<input type= "hidden" name= "action" value= "unsubmitted"/>
<input type= "button" Name= "Submit" value= "execute" onclick= "query ();"><!--to get user data and send it to the server via Ajax-->
<label></label>
<label></label>
</center>
</form></td>
</tr>
</table>

<span id= "res" ></span>
</center>
</body>

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.