Fetching a Response


The real power of Ajax doesn't come from the code in your Web page, but in the support files that stay on the server. Retrieving chunks of data (described in the previous section) can be useful, but to create an Ajax Web page that truly interacts with the user, you need to be able to both send to the server as well as receive data back from it.

In this section, we'll continue building on the fetchData() function from the previous section by adding the capability to not only GET data from the server, but POST data to it as well.

In the next example (Figure 20.4), the visitor can click on their planet of origin. The planet's number is sent to the data page, which then returns a custom message for that planet (Figures 20.5 and 20.6).

Figure 20.4. The page loads with the controls.


Figure 20.5. Depending on the planet you click, you will get a different message retrieved from the server.


Figure 20.6. Click a different planet (or former planet), and get a different message.


Keep in mind that in all the examples in this book, I'm using PHP for my server side files. Not all Web servers are set up to handle PHP, so if you are not sure, then check with your server administrator. If you do not have PHP on your Web server, then these examples will not work.

To fetch a data response from the server:

1.

dataPage.php


Create your data page and save it as dataPage.php (Code 20.3).

Code 20.3. dataPage.php: The data page contains a simple PHP example that takes the posted value out of the HTTP headers and then delivers back a message based on that value.

[View full width]

<?php if(isset($_POST["sendData"])) { $searchString = $_POST["sendData"];     if ($searchString == 1) $dataResults = sprintf("<h1>Hello Mercury!</h1>");     else if ($searchString == 2) $dataResults = sprintf("<h1>Hello Venus!</h1>");     else if ($searchString == 3) $dataResults = sprintf("<h1>Hello Earth!</h1>");     else if ($searchString == 4) $dataResults = sprintf("<h1>Hello Mars!</h1>");     else if ($searchString == 5) $dataResults = sprintf("<h1>Hello Jupiter!</h1>");     else if ($searchString == 6) $dataResults = sprintf("<h1>Hello Saturn!</h1>");     else if ($searchString == 7) $dataResults = sprintf("<h1>Hello Uranus!</h1>");     else if ($searchString == 8) $dataResults = sprintf("<h1>Hello Neptune!</h1>");     else if ($searchString == 9) $dataResults = sprintf("<h2>Sorry Pluto… You aren't a  planet anymore.</h2>");     else $dataResults = sprintf("<p>You are no longer in the solar system.</p>"); } echo $dataResults; ?>

In this example, I've used PHP to create a simple logical structure that will evaluate the value of the variable sent to the data page from the Web page through the sendData variable:

$searchString = $_POST["sendData"];

2.

index.html


Create an HTML file and save it as index.html (Code 20.4). The rest of the steps in this example apply to this file.

Code 20.4. index.html: The fetchData() function passes a value to the data page on the server and then displays the results it returns.

[View full width]

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR /xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>CSS, DHTML &amp; Ajax | Fetching a Data Response</title> <style type="text/css" media="screen"> h1 { color: red; } #control {      float: left;      cursor: pointer;      margin-right: 4px;      color: red;      background-color: #fcc;      border: 1px solid red;      padding: 4px; } </style> <script type="text/javascript"> function fetchData(url,dataToSend,objectID){     var pageRequest = false     if (window.XMLHttpRequest) pageRequest = new XMLHttpRequest();     else if (window.ActiveXObject) pageRequest = new ActiveXObject("Microsoft.XMLHTTP");     else return false;     pageRequest.onreadystatechange = function() {       var object = document.getElementById(objectID);       object.innerHTML = pageRequest.responseText;     }     if (dataToSend) {        var sendData = 'sendData=' + dataToSend;     pageRequest.open('POST',url,true);     pageRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');     pageRequest.send(sendData);     }     else {     pageRequest.open('GET',url,true);     pageRequest.send(null); }} </script> </head> <body> <p>What Planet are you from?</p> <div id="control" onclick="fetchData('dataPage.php',1, 'message');"> Mercury </div> <div id="control" onclick="fetchData('dataPage%.php',2, 'message');"> Venus </div> <div id="control" onclick="fetchData('dataPage%.php',3, 'message');"> Earth </div> <div id="control" onclick="fetchData('dataPage%.php',4, 'message');"> Mars </div> <div id="control" onclick="fetchData('dataPage%.php',5, 'message');"> Jupiter </div> <div id="control" onclick="fetchData('dataPage%.php',6, 'message');"> Saturn </div> <div id="control" onclick="fetchData('dataPage.php',7,'message');"> Uranus </div> <div id="control" onclick="fetchData('dataPage%.php',8, 'message');"> Neptune </div> <div id="control" onclick="fetchData('dataPage%.php',9, 'message');"> Pluto </div> <p>&nbsp;</p> <div id="message">&nbsp;</div> </body> </html>

3.

function fetchData (url, dataToSend, objectID) {…}


Add the function fetchData() to a JavaScript block.

This function is identical to the fetchData() function presented in the previous section, but adds the ability to send information to the data page as well as receive data back from it. Steps 4 through 8 apply to this function.

4.

if (dataToSend) {…}


If data is being sent back to the server from the page (dataToSend is not null):

var sendData = 'sendData=' + dataToSend;


Initialize the variable sendData, which stores a string with the dataToSend value assigned to the sendData variable. This string is passed along to the data page.

5.

pageRequest.open('POST', url, true);


Open a conduit to the data page, but rather than using GET you will be using the POST method to send data along with the request.

pageRequest.setRequestHeader ('Content-Type', 'application/x-www-form-urlencoded');


6.

pageRequest.send(sendData);


Set the header that will be sent with the request. Send the data to the data page you set up in Step 1, using the sendData variable.

7.

else {…}


If no data is being sent to the page, then we use the GET method as specified in Step 8 of the previous section ("Fetching Data").

8.

onclick = "fetchData('dataPage.php', 3, 'message');"


Add an event handler to your HTML to trigger the fetchData() function.

In this example, I set up a simple onclick event handler to trigger the function when the visitor clicks one of the controls. The event sends to the function the URL for the page where the data is located (dataPage.php), a value that will be sent to the data page and used to determine its response (if you want to simply fetch a data chunk, pass the value null), and the ID for the object to have the results placed into (message).

9.

<div id="message">&nbsp;</div>


Finally, set up the object that will contain the final results fetched using our Ajax function from Step 3.




CSS, DHTML and Ajax. Visual QuickStart Guide
CSS, DHTML, and Ajax, Fourth Edition
ISBN: 032144325X
EAN: 2147483647
Year: 2006
Pages: 230

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net