27.10.2015 Views

AJAX and PHP

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Client-Side Techniques with Smarter JavaScript<br />

}<br />

}<br />

}<br />

// (use xmlHttp.responseXML to read an XML response as a DOM object)<br />

// do something with the response<br />

// ...<br />

// ...<br />

Once again we can successfully use try/catch to h<strong>and</strong>le errors that could happen while initiating a<br />

connection to the server, or while reading the response from the server.<br />

A safer version of the h<strong>and</strong>leRequestStateChange method looks like this:<br />

// function executed when the state of the request changes<br />

function h<strong>and</strong>leRequestStateChange()<br />

{<br />

// continue if the process is completed<br />

if (xmlHttp.readyState == 4)<br />

{<br />

// continue only if HTTP status is "OK"<br />

if (xmlHttp.status == 200)<br />

{<br />

try<br />

{<br />

// retrieve the response<br />

response = xmlHttp.responseText;<br />

// do something with the response<br />

// ...<br />

// ...<br />

}<br />

catch(e)<br />

{<br />

// display error message<br />

alert("Error reading the response: " + e.toString());<br />

}<br />

}<br />

else<br />

{<br />

// display status message<br />

alert("There was a problem retrieving the data:\n" +<br />

xmlHttp.statusText);<br />

}<br />

}<br />

}<br />

OK, let's see how these functions work in action.<br />

Time for Action—Making Asynchronous Calls with XMLHttpRequest<br />

1. In the foundations folder, create a subfolder named async.<br />

2. In the async folder, create a file called async.txt, <strong>and</strong> add the following text to it:<br />

Hello client!<br />

3. In the same folder create a file called async.html, <strong>and</strong> add the following code to it:<br />

<br />

<br />

<br />

<strong>AJAX</strong> Foundations: Using XMLHttpRequest<br />

<br />

<br />

<br />

Hello, server!<br />

50<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!