FASTER, HIGHER, FARTHER Eb 2.0 Isn’T Only About the User Experience
Total Page:16
File Type:pdf, Size:1020Kb
COVER STORY AJAX Programming websites with AJAX FASTER, HIGHER, FARTHER eb 2.0 isn’t only about the user experience. Several important new developer tools are Walso helping to create faster and more effi- cient websites. One of the most important features of the new Internet is a technology known as AJAX. On the old Internet, if you filled out a web form with several input fields and sent it to the server, you were expected to wait while the server evaluated your input and responded with a new page (Figure 1). An AJAX- based website provides a more elegant solution. In- stead of re-requesting the whole page, the web browser simply requests a small fragment of the page. The user continues to work as the request if filled by the server, and the browser goes on to merge the data with the ex- isting page. In the user’s experience, the website is al- most as fast as a desktop application. The name AJAX was coined by Jesse James Garrett [1] in his essay “AJAX: A New Approach to Web Appli- cations.” Although Garrett maintains that AJAX is not an acronym, most people take as a shortcut for Asyn- chronous Javascript and XML. AJAX websites are not built from static HTML files (and CSS stylesheets), but are, instead, comprised of Javascript code that runs when a user clicks a link or triggers some other kind of event. Javascript functions request data from the server, AJAX offers a fast and efficient approach for building which returns the XML (this explains the X) and HTML- interactive websites. We’ll show you how to call upon formatted data, along with other formats. This article provides a hands-on look at how to put the powers of AJAX for your own web creations. AJAX to work for your own website. BY OLIVER FROMMEL Asynchronous Because the AJAX request is asynchronous (this ex- plains the A), the user can continue to interact with other parts of the HTML page without blocking the browser. An asynchronous request emancipates the re- quest from the response. Once the browser’s Javascript code has issued a request, it just goes on running. When the response reaches the browser, it calls a spe- cific Javascript function, which in turn merges the re- sult with the existing HTML page. The result can be as simple as a single numeric value in an HTML table, structured data in XML or JSON (Javascript Object No- tation), or a form value. This technique gives Google Mail the ability to use workspace at the center of the browser to display an editor where the user can compose a message, display a message, or display a list of messages (Figure 2). 24 WWW.LINUX - MAGAZINE.COM AJAX COVER STORY Other good examples of AJAX are the Web 2.0 apps Flickr and Del.icio.us. Quick Start 1 To get us started, let’s take a look at a 1 very simple web application. When the user clicks, we want the browser to download a random number from the new server and display the number at a pre- 2 new 2 Server Server defined position on the web page. The application comprises three com- 3 3 ponents: the static HTML front page, the Javascript code, and a server-side script 4 4 that returns the results (the random new number). One thing you definitely need new for this is a web server (typically Apache) that supports a scripting lan- guage – this will be PHP in our example. However, you can run the server and the browser on the same machine – any nor- mal desktop will do – to try AJAX out. Figure 1: The legacy approach: the browser Figure 2: The AJAX model: requests only If installing and configuring Apache reloads the page completely whenever a reload the parts of a page that have actually and PHP with your distribution’s stan- change occurs. changed. dard tools is too complex, just pick one of the popular LAMP or XAMPP pack- when the user clicks it. This is followed the link, the browser pops up a dialog ages. The packages include Apache and by an HTML span with an ID, which the that displays a text message of Clicked. PHP, along with the MySQL database, Javascript will reference later. If this doesn’t work, at least you can which, strictly speaking, you do not If you want to test whether the HTML/ practice troubleshooting. The Firefox need, although it can come in handy for Javascript connection is working, add browser is a good choice for develop- dynamic AJAX applications. the following code to the file: ment work with AJAX, as it includes a The HTML file in the AJAX sample ap- collection of practical tools. For example, plication has a simple structure (Listing function getRandom() the Tools menu has a JavaScript Console 1). The script tag in the header section { item that pops up a small window for points to an external Javascript file, ti- alert("Clicked"); Javascript error messages. tled ajax.js, which contains the code for } A simple application like this does not the AJAX application. As an alternative have many potential sources of error. to this, you can insert Javascript func- Assuming that index.html and ajax.js are The server may not be able to locate the tions between the opening and closing located in the same server directory, ajax- Javascript file, or the problem could be a script tags in the body of the HTML file. test for example, the URL for the HTML syntax error. Line 6 in Listing 1 links the code and page would be http://Servername/ajax- the HTML. The link’s onclick attribute test/. If the server and browser are run- Connecting with the Server stores the name of the Javascript func- ning on the same machine, use localhost Thus far, the browser has sent one re- tion called by the browser (getRandom) as the server name. Now, when you click quest each for the HTML page and the Advertisement COVER STORY AJAX Javascript file to the server. This com- Listing 2: The Complete If you don’t see a dialog, it’s back to pletes the communication. The two do troubleshooting: a typo in the URL vari- Listing not contact each other when a user able, possibly? Copy the string (without clicks a link. To retrieve more data from 01 function checkResult() the quotes), insert it into the address box the server, the Javascript code first has 02 { in another browser window, and press to create a request object. The XML- the Enter key. If the server responds with 03 alert("New state: " + HttpRequest() handles this and also ex- request.readyState); an error message, compare the variable plains the X in AJAX. The following with the filename on the server once 04 } command assigns the new request object again. to the request variable: 05 The security settings for Javascript in 06 function getRandom() { your browser are another potential request = U 07 request = new source of error: the request object can new XMLHttpRequest(); XMLHttpRequest(); only contact the server that served up 08 var url = "http:// the original HTML page. If the server ad- The request object has a number of localhost/~oliver/ajax/index. dresses differ, the browser will assume a methods that are important for commu- html"; security infringement and issue a “Per- nicating with the server later on. First of 09 request.open("GET", url, mission denied” message. all, request.open() sets the connection true); A Firefox extension titled Firebug can parameters. 10 request.onreadystatechange be useful for troubleshooting AJAX ap- The first parameter specifies the HTTP = checkResult; plications [2]. It not only shows you the method (GET or POST); this is followed 11 request.send(null); Javascript errors but can give you every by the web address (URL) to contact. 12 } single XMLHttpRequest with the header The next parameter is for asynchronous fields and response code. access with a value of true) in our case. Two optional parameters can pass in the echange field is used to specify the call- Payload username and password for password- back function. Of course, these simple examples are not protected pages. Assuming an address of As the name would suggest, the exactly what AJAX’s inventor intended. http://localhost/~oliver/ajax/test.php in browser does not just call the callback Background server requests are designed the Javascript variable url, the following function when it receives a response, but to merge dynamic content with the cur- line sets up the connection: whenever the request object state has rent website. The PHP script in Listing 3 changed. Five states are defined for the implements a test service for this pur- request.open("GET", url, true); request object, ranging from unused (0) pose, issuing a random number between to finished (4). 1 and 100 for each request. Before you send the request to the If you store the script as random.php server, you first have to specify the func- Waiting for Responses in the same server directory as the other tion the browser calls when it receives Finally, let’s use the send method to files, you need to change the url variable the response. You may recall that the send the request to the server; the in ajax.js to match. This gives you the browser will not wait for the server re- method can handle any payload data following line: sponse, as communications between the you may have as optional parameters, browser and the server are asynchro- giving you the ability to insert user input var url = "http://localhost/U nous.