The real power of Ajax involves code on the server because that’s what Ajax is all about: interacting with the server. And to make things happen on the server, you need to use server-side code. This book uses PHP (hypertext preprocessor) for its server-side code, but don’t worry, you won’t have to know PHP to read this book (although Chapter 11 introduces PHP and Ajax). The PHP used here is basic, and if you know JavaScript, you’ll be able to figure it out.
This book uses PHP because it’s the most common choice for connecting to Ajax. PHP is easy to write and easy to use. There are thousands of Web servers that support PHP, so if you want to sign up for one, they’re easy to find. Your current server may already support PHP because most do these days _ just ask them. For testing purposes, you can also install PHP on your own machine. You can get PHP for free at www.php.net, complete with installation instructions (on Windows, installing can be as easy as running a .exe file).
For example, say that instead of downloading text from a static file, data.txt, you had this PHP script, data.php, installed on the server:
<?php echo 'This text was also fetched from the server with Ajax.'; ?>
This script sends (echoes) the text “This text was also fetched from the server with Ajax” back to the browser, so you should be able to display that text in your Ajax application if you fetch it from the server. Fetching that text from the server is easy; all you need to do is fetch data from the URL data.php, not data.txt, as you see here in index3.html:
<html> <head> <title>An Ajax demo</title> <script language = "javascript"> var XMLHttpRequestObject = false; if (window.XMLHttpRequest) { XMLHttpRequestObject = new XMLHttpRequest(); } else if (window.ActiveXObject) { XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP"); } function getData(dataSource, divID) { if(XMLHttpRequestObject) { var obj = document.getElementById(divID); XMLHttpRequestObject.open("GET", dataSource); XMLHttpRequestObject.onreadystatechange = function() { if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) { obj.innerHTML = XMLHttpRequestObject.responseText; } } XMLHttpRequestObject.send(null); } } </script> </head> <body> <H1>An Ajax demo</H1> <form> <input type = "button" value = "Fetch the message" onclick = "getData('data.php', 'targetDiv')"> </form> <div > <p>The fetched message will appear here.</p> </div> </body> </html>
You can see this Web page, index3.html, in Figure 3.3.
Figure 3.3: Reading text from a PHP script using Ajax
When the user clicks the button in this page, the text from the PHP script, data.php, is downloaded and displayed, as shown in Figure 3.4. Presto! You’re working with online server-side scripts and Ajax. Not bad.
Figure 3.4: Downloading text from a PHP script