Using Ajax JavaScript via PHP and Sajax

Source: Internet
Author: User
Tags object error handling functions variables php and variable window ibm developerworks
Ajax|javascript for years, the goal of creating truly responsive Web applications has been hampered by a simple fact of web development: To change the information on one part of a page, users must overload the entire page. But it won't happen again. Thanks for 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 for PHP and introduces the Simple AJAX Toolkit (SAJAX), a tool written in PHP that integrates server-side PHP with JavaScript.

   before you start

This tutorial is for people interested in developing rich Web applications, where rich Web applications combine asynchronous JavaScript with XML (Ajax) and PHP, so that users can dynamically update content each time they click without refreshing the entire page. This tutorial assumes that the reader understands basic PHP concepts, including if and switch statements, and the use of functions.

   about this tutorial

In this tutorial, you will learn about Ajax and the issues surrounding its application. An AJAX application will be built in PHP to display the panels in a previously written tutorial. Clicking on the Panel link will only reload the content area and replace it with the contents of the selected panel, saving bandwidth and page loading time. The Simple AJAX Toolkit (SAJAX) is then integrated into an AJAX application that synchronizes the use of Ajax and simplifies development.

   Overview

Before going deep, look at Ajax, sample PHP applications, and Sajax. Ajax

Ajax allows web developers to create interactive Web pages, while avoiding the need to wait for pages to load this bottleneck. An application created with Ajax allows you to replace the content of a particular area of a Web page with new content by simply clicking the button. What's wonderful about it is that you don't have to wait for the page to load, only the content of this area needs to be loaded. Take Google Maps As an example: You can click and move around the map without waiting for the page to load.

   problems with Ajax

There are things to be aware of when using Ajax. Ajax pages, like other Web pages, can be bookmarked, so it creates problems when you use Get and POST to make a request. The increase in the number of internationalization and coding schemes has made it increasingly important to standardize these coding schemes. These are important questions to be learned in this tutorial.

Sample PHP Application


First you create an application with Ajax and then create it with Sajax to show the benefits of using the toolkit. The application is part of a previously written tutorial with a panel link. It is used as an example to demonstrate the advantages of using Ajax. Because when clicked on each panel, they are loaded asynchronously without having to wait for the rest of the page to mount again. The sample application also shows how to create your own Ajax application.

   Sajax

If you want to create an AJAX application, you don't want to be tired of the complexity of Ajax details. The answer is Sajax. By using libraries developed by Modernmethod people, Sajax abstracts the high-level details of Ajax for WEB developers. On the ground floor, Sajax works the same as Ajax. However, by using the high-level functions provided by the Sajax library, you can ignore the technical details of Ajax.

   What is Ajax?

This section is an introductory introduction, using an example to explain the concept of Ajax, including what happens when you click on the link, and the HTML and JavaScript code that AJAX needs for your PHP application. The next section is a bit more in-depth and actually creates PHP applications using the Ajax concepts learned in this section.

   behind-the-scenes content

Ajax is a combination of asynchronous JavaScript and XML. Asynchronous, because you can click on the link on the page, and then it only loaded with the click of the corresponding content, while keeping the title or any other set of information does not move.

When you click on the link, the JavaScript function works behind it. JavaScript creates an object that communicates with a Web browser and tells the browser to mount a specific page. You can then browse other content on the same page as you normally would, and when the browser is fully loaded into the new page, the browser displays the content in the location specified by the HTML div tag.

CSS style codes are used to create links with span tags.

   CSS Style Code

The sample application requires CSS code so that the span tag looks like using a regular anchor tag (<a Href= ...). > as the real link is created, it will be clicked like a real link.

Listing 1. Specify display information for span markers

...

These span tags are used in the sample application, and the colors match the colors used by links in all IBM developerWorks tutorials. The first line of the style tag specifies that the colors of the links you have visited remain unchanged. When the mouse is crossed, the cursor becomes a pointer, just like an ordinary anchor tag (<a href ...). >) the same. Now let's see how to create a link that uses this CSS style code.

   Create a link that uses a span tag

The link to create in the "Build PHP Application" section will be used to communicate with the browser through JavaScript, telling the browser where to go and what to extract. Instead of traditional links that use anchor tags, they are created using span tags. The perception of span tags is determined by the CSS code in Listing 1. Here is an example:

managing Content

The onclick handler specifies which script to run when this span is clicked. There are several other indicators similar to the onclick that can be used, including onmouseover and ondblclick. Notice that JavaScript function loadhtml is displayed in the onclick field instead of the traditional http://link or by listing panels-ajax.php? The relative link created. Next, learn the loadhtml function.

   XMLHttpRequest Objects

If you are using one of the Mozilla, Opera, or other browsers, you can use the built-in XMLHttpRequest object to dynamically get content. Microsoft's Internet Explorer browser uses another object that will be learned later. They are used in the same way, and support them, just adding a few lines of extra code.

The XMLHttpRequest object is used to retrieve page content through JavaScript. This code will be used later in the sample application, in conjunction with the ActiveXObject loadhtml function. See Listing 2 for usage.

Listing 2. Initializing and using the XMLHttpRequest object

...

The destination variable passed as a parameter in Listing 2 indicates where the XMLHttpRequest object is to be loaded, specified by the <div id= "content" </div> tag. The code then checks to see if the XMLHttpRequest object exists, and if so, creates a new one. The event handler is then set to the Processstatechange function, which is the function that the object will call every time the state changes. The rest of the request is set using the Open method, setting the transport type to get, and setting the URL to which the object will be mounted. Finally, the Send method of the object is invoked, allowing the object to actually play its part.

ActiveXObject

In Internet Explorer, replace XMLHttpRequest with ActiveXObject. Its functions are the same as XMLHttpRequest functions, and even the function names are the same, as shown in Listing 3.

Listing 3. Initialization and use of 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 ();
}
}
}

In this case (using Internet Explorer), instantiate a new ActiveXObject object of the Microsoft.XMLHTTP type. Then, set the event handler to invoke the object's open function. Then call the object's send function so that ActiveXObject works.

   Processstatechange function

The function described here is called an event handler or a callback function. The purpose of the callback function is to be able to handle state changes when the state of the object is changed. In specific applications, the purpose of this function should be to deal with state changes, verify that the object arrives at the expected state, and read dynamically loaded content.

The Processstatechange function is invoked by a XMLHttpRequest or ActiveXObject object when the state of the object has changed. When the object enters State 4 o'clock, the content of the page has been received (see Listing 4).

Listing 4. Handling state 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 arrives at state 4 o'clock, the content is ready to be extracted and displayed at the intended location of the browser. The location is contentdiv and the content is retrieved from the document. If the request is correct and is retrieved in the correct order, then the response should be in the state of 200. The HTML response is saved in Request.responsetext, set to contentdiv.innerhtml, and can be displayed in the browser.

If there is no error in the transmission process, everything is OK, then the new content will appear in the browser, otherwise, request.status is 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;
}
...

Listing 5 sends the information about the transmission error to the browser. This function will be used as a callback function in the sample application. Next, learn about the problems of get and POST and their differences.

   Get and POST

Get and POST are two ways to make HTTP requests and pass variables in the request. Developers should not randomly choose which method to use, since both methods are useful. Get requests embed variables in the URL, which means they can be bookmarked. This method can have side effects if the variable may modify the database, purchase the product, or do something similar. If the accidentally bookmarked page has a URL for the item that contains the address, credit card number, and $ $, all embedded in the URL, then re-access to the URL means to buy the product.

Therefore, a GET request can be made only if the variable has no side effects and can be loaded back in often and nothing happens. A variable that is suitable for a GET request may be a category ID. You can reload it over and over again, and the category will be repeated, but without any cumulative effect.

On the other hand, a POST request should be used when a variable is useful for a source, such as a database, or for personal information security. For example, when purchasing a product of $ A, POST request should be used. If you bookmark the payment page, nothing happens because there are no variables in the URL, and you don't accidentally buy something you don't want to buy, or you buy it again if you already have it.

The meaning of Get and POST has the same effect in Ajax. It is important to understand the differences between get and POST requests when building the application and future applications of this article. This can help avoid common pitfalls of WEB application development.

   Coding Method

There are several ways to encode data transmitted over HTTP, and XML accepts only a few of them. One of the most important coding methods for interoperability is UTF-8, because it is backward compatible with the U.S. Information Interchange Standard Code (ASCII). Many of the international characters used in other countries are encoded in a way that is not backwards compatible with ASCII, and is not appropriate to be placed in an XML file without proper coding.

For example, putting a string "internationalization" in a browser and encoding it with UTF-8 will turn it into a i%f1t%ebrn%e2ti%f4n%e0liz%e6ti%f8n. 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 to choose from.

It is important to understand this because coding issues are handled during the transmission and reception of documents over HTTP, as are the case with Ajax. When using Ajax for transmission, you should also use UTF-8 encoding, because standardization improves interoperability.

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.