Use Ajax through PHP and sajax (1)
How to integrate server-side PHP with JavaScript with the simple Ajax Toolkit
Taylor Anderson, Freelance Author, stexar
May 11, 2006
Over the years, the goal of creating truly responsive Web applications has been blocked by a simple fact in Web development: to change the information of a part of a page, you must reload the entire page. But this will not happen again in the future. Thanks to asynchronous Java scripts and XML (Ajax), we can now request new content from the server side and modify only part of the page. This tutorial explains how to use Ajax in PHP and describes the simple Ajax Toolkit (sajax). This is a tool written in PHP that can integrate PHP on the server with JavaScript.
Before getting started
This tutorial is intended for those interested in developing rich web applications. Rich Web applications combine Asynchronous JavaScript and XML (Ajax) with PHP. Each time a user clicks, content can be dynamically updated without refreshing the entire page. This tutorial assumes that the reader understands the basic PHP concepts, includingif
Andswitch
Statement and function usage.
About this tutorial
In this tutorial, I will learn about Ajax and its application. An Ajax application will be built using PHP to display the panel in the previous tutorial. Clicking the Panel link will only reload the content area and replace it with the content of the selected panel, thus saving the bandwidth and page loading time. The simple Ajax Toolkit (sajax) is then integrated into the Ajax application, which can be used synchronously to simplify development.
Overview
Before proceeding, let's take a look at Ajax, the sample PHP application, and sajax.
Ajax
Ajax allows web developers to create interactive web pages, while avoiding the bottleneck of waiting for page loading. For an application created using Ajax, you only need to click the button to replace the content in a certain area of the Web page with the new content. It is wonderful that you do not have to wait for page loading. Only the content in this area needs to be loaded. Taking Google maps as an example: You can click and move a map around without waiting for the page to load.
Ajax Problems
Pay attention to some issues when using Ajax. Like other web pages, Ajax pages can be bookmarked.GET
AndPOST
The request may cause problems. The increasing number of internationalization and encoding schemes makes it increasingly important to standardize these encoding schemes. These important questions will be learned in this tutorial.
Example PHP application
First, create an application using Ajax and then use sajax to demonstrate the benefits of using this toolkit. An application is part of a previous tutorial with a panel link. It is used as an example to demonstrate the advantages of Ajax. The reason is that when you click on each panel, they are asynchronously loaded without waiting for the remaining part of the page to be loaded again. This sample application also shows how to create your own Ajax application.
Sajax
If you want to create an Ajax application, you do not need to be tired of complicated Ajax details. The answer is sajax. By using the library developed by modernmethod, sajax abstracts high-level Ajax details for Web developers. At the underlying layer, sajax works the same as Ajax. However, you can ignore the technical details of Ajax by using the high-level functions provided by the sajax library.
What Is Ajax?
This section is an introductory introduction. It uses examples to explain Ajax concepts, including what happens When you click a link. Ajax is used for HTML and JavaScript code required by PHP applications. The next section will be more in-depth. We will actually use the Ajax concepts learned in this section to create PHP applications.
Background content
Ajax is a combination of Asynchronous JavaScript and XML. The reason for Asynchronization is that you can click the link on the page, and then it only loads the content corresponding to the click, while keeping the title or any other set information unchanged.
When you click the link, the JavaScript function is used. Javascript creates an object that communicates with the web browser and tells the browser to load a specific page. Then, you can browse other content on the same page as usual. When the browser loads a new page completely, the browser willdiv
Mark the specified position to display the content.
The CSS style code is used to create a link with the span tag.
CSS style code
The sample application requires CSS code, so that the span tag looks like a regular anchor tag (<a href=... >
.
Listing 1. Specify the display information of the span tag
...<style type="text/css"> span:visited{ text-decoration:none; color:#293d6b; } span:hover{ text-decoration:underline; color:#293d6b; } span {color:#293d6b; cursor: pointer}</style>
|
These span tags are used in the sample application to match the colors used by links in all IBM developerworks tutorials. The first line of the STYLE tag specifies that the color of the accessed link remains unchanged. The mouse is underlined and the cursor becomes a pointer, just like a normal anchor mark (<a href... >
. Now let's take a look at how to create a link using this CSS style code.
Create a link marked with span
The link to be created in the "build a PHP application" section is used to communicate with the browser through JavaScript, telling the browser where to go and what content to extract. They are created using the span tag instead of the traditional link that uses the anchor tag. The perception of the span tag is determined by the CSS code in Listing 1. Here is an example:
<span onclick="loadHTML('panels-ajax.php?panel_id=0', 'content')">Managing content</span>
|
onclick
The handler specifies the script to run when the span is clicked. There are several otheronclick
Similar indicators can be used, includingonmouseover
Andondblclick
. Note that the onclick field displays JavaScript Functions.loadHTML
Instead of traditionalhttp://
Link or by listpanels-ajax.php?
The relative link. Next we will learnloadHTML
Function.
XMLHTTPRequest object
If you are using Mozilla, opera, or one of other browsers, you can use the built-inXMLHttpRequest
The object dynamically retrieves the content. Microsoft Internet Explorer uses another object, which will be learned later. They are actually used in the same way, and they are supported, just a few additional lines of code.
XMLHttpRequest
Objects are used to retrieve page content through JavaScript. This code will be used in the sample application laterActiveXObject
OfloadHTML
Function. See list 2 for usage.
Listing 2. Initializing and using XMLHttpRequest objects
...<style><script type="text/javascript">var request;var dest;function loadHTML(URL, destination){ dest = destination; if(window.XMLHttpRequest){ request = new XMLHttpRequest(); request.onreadystatechange = processStateChange; request.open("GET", URL, true); request.send(null); }}</script>...
|
Passed as a parameter in Listing 2destination
Variable descriptionXMLHttpRequest
Where the object is to be loaded<div id="content"></div>
Mark specified. Then the code will checkXMLHttpRequest
Whether the object exists. If yes, a new one is created. Then, the event handler is setprocessStateChange
Function. This function is called every time the object changes its status. The rest of the request is to useopen
Method, set the transmission typeGET
And set the URL of the object to be loaded. Finally,send
Method To make the object actually play a role.
Activexobject
In Internet Explorer, useActiveXObject
ReplaceXMLHttpRequest
. Its functions andXMLHttpRequest
And even the function names are the same, as shown in listing 3.
Listing 3. Initializing and using activexobject
...function loadHTML(URL, destination){ dest = destination; if(window.XMLHttpRequest){... } else if (window.ActiveXObject) { request = new ActiveXObject("Microsoft.XMLHTTP"); if (request) { request.onreadystatechange = processStateChange; request.open("GET", URL, true); request.send(); } }}</script>
|
In this case (using Internet Explorer), instantiateMicrosoft. XMLHTTP type
NewActiveXObject
Object. Then, set the event handler to callopen
Function. Then,send
Function.ActiveXObject
Work now.
Processstatechange Function
The function described here is called an event handler or callback function. The purpose of the callback function is to handle state changes when the object state changes. In a specific application, the purpose of this function is to handle state changes, check whether the object has reached the expected state, and read the content Dynamically Loaded.
processStateChange
FunctionXMLHttpRequest
OrActiveXObject
An object is called when its status changes. When the object enters status 4, the page content has been received (see Listing 4 ).
Listing 4. Handling status changes
...var dest;function processStateChange(){ if (request.readyState == 4){ contentDiv = document.getElementById(dest); if (request.status == 200){ response = request.responseText; contentDiv.innerHTML = response;http://httpd.apache.org/download.cgi } }}function loadHTML(URL, destination){...
|
When the xml http object reaches status 4, the content is ready and can be extracted and displayed in the browser's expected position. Location iscontentDiv
, The content is retrieved from the document. If the request is correct and retrieved in the correct order, the response status should be 200. HTML response is saved inrequest.responseText
, Set itcontentDiv.innerHTML
In the browser.
If no error occurs during transmission and everything is normal, the new content will appear in the browser; otherwise,request.status
Not equal to 200. See listing 5 for error handling code.
Listing 5. Error Handling
... if (request.status == 200){ response = request.responseText; contentDiv.innerHTML = response; } else { contentDiv.innerHTML = "Error: Status "+request.status; }...
|
In listing 5, information about transmission errors is sent to the browser. This function will be used as a callback function in the example application. Next, learnGET
AndPOST
And their differences.
Get and post
GET
AndPOST
Is an HTTP request and a variable is passed in the request. Developers should not choose which method to use, because both methods are meaningful.GET
The request embeds the variables in the URL, which means they can be bookmarked. This method has side effects if the variable may modify the database, purchase the product, or perform other similar operations. Assume that the page with accidentally added bookmarks has a URL for the purchased item, which contains the address, credit card number, and $100 products, all of which are embedded in the URL, then re-access to this URL means to purchase this item.
Therefore, it can be performed only when the variables have no side effects and can be reloaded frequently.GET
Request. SuitableGET
A variable in the request may be the category ID. It can be re-loaded repeatedly, and the classification is displayed repeatedly, but there is no cumulative effect.
On the other hand, when a variable is used for the source (such as a database) or for personal information securityPOST
Request. For example, you must usePOST
Request. If you add bookmarks to the payment page, nothing will happen because there is no variable in the URL, and you will not accidentally buy anything you don't want to buy, or you can buy it again if you already have it.
GET
AndPOST
The significance has the same effect in Ajax. When building the applications and future applications in this article, understandGET
AndPOST
The difference in requests is very important. This helps avoid common defects in Web application development.
Encoding Method
There are multiple methods to encode data transmitted over HTTP, while XML only accepts a few of them. One of the most interoperable encoding methods is UTF-8, because it is backward compatible with American Information Interchange Standard Code (ASCII ). Many international character encoding methods used in other countries are not backward compatible with ASCII. If they are not properly encoded, they are not suitable for XML files.
For example, placing the string "Internationalization" in a browser will change it to I % f1t % ebrn % e2ti % f4n % e0liz % e6ti % f8n if it is encoded in a UTF-8. The UTF-8 encoding of the classic ASCII character corresponds to the 7-bit ASCII code of the same character, which makes the UTF-8 an ideal encoding method.
It is important to understand this, because the encoding problem must be handled during the transmission and receipt of documents through HTTP, and the same is true when Ajax is used. UTF-8 encoding should also be used when using Ajax for transmission, because standardization can improve interoperability.
Note:
This article from: http://www.ibm.com/developerworks/cn/views/opensource/tutorials.jsp? Ct_doc_id = 109065
Copyright belongs to IBM. This blog is only for reprinting and learning more technical purposes.