Use Ajax through PHP and sajax (1)

Source: Internet
Author: User
Tags ibm developerworks

 

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, includingifAndswitchStatement 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.GETAndPOSTThe 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 willdivMark 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>

onclickThe handler specifies the script to run when the span is clicked. There are several otheronclickSimilar indicators can be used, includingonmouseoverAndondblclick. Note that the onclick field displays JavaScript Functions.loadHTMLInstead of traditionalhttp://Link or by listpanels-ajax.php?The relative link. Next we will learnloadHTMLFunction.

 

XMLHTTPRequest object

If you are using Mozilla, opera, or one of other browsers, you can use the built-inXMLHttpRequestThe 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.

XMLHttpRequestObjects are used to retrieve page content through JavaScript. This code will be used in the sample application laterActiveXObjectOfloadHTMLFunction. 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 2destinationVariable descriptionXMLHttpRequestWhere the object is to be loaded<div id="content"></div>Mark specified. Then the code will checkXMLHttpRequestWhether the object exists. If yes, a new one is created. Then, the event handler is setprocessStateChangeFunction. This function is called every time the object changes its status. The rest of the request is to useopenMethod, set the transmission typeGETAnd set the URL of the object to be loaded. Finally,sendMethod To make the object actually play a role.

 

Activexobject

In Internet Explorer, useActiveXObjectReplaceXMLHttpRequest. Its functions andXMLHttpRequestAnd 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 typeNewActiveXObjectObject. Then, set the event handler to callopenFunction. Then,sendFunction.ActiveXObjectWork 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.

processStateChangeFunctionXMLHttpRequestOrActiveXObjectAn 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.innerHTMLIn the browser.

If no error occurs during transmission and everything is normal, the new content will appear in the browser; otherwise,request.statusNot 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, learnGETAndPOSTAnd their differences.

 

Get and post

GETAndPOSTIs an HTTP request and a variable is passed in the request. Developers should not choose which method to use, because both methods are meaningful.GETThe 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.GETRequest. SuitableGETA 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 securityPOSTRequest. For example, you must usePOSTRequest. 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.

GETAndPOSTThe significance has the same effect in Ajax. When building the applications and future applications in this article, understandGETAndPOSTThe 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.

 

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.