13.09.2016 Views

PHP and MySQL Web Development 4th Ed-tqw-_darksiderg

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

864 Chapter 34 Building <strong>Web</strong> 2.0 Applications with Ajax<br />

the current server time based on the 24-hour clock, <strong>and</strong> once as date('M d, Y'),<br />

which returns the month, date, <strong>and</strong> year the script was called.<br />

The result string itself will look like the following, with the items in brackets replaced<br />

by the actual values:<br />

<br />

<br />

<br />

It is [time] on [date].<br />

<br />

<br />

In the next section, you’ll create the remaining function, theHTTPResponse(), <strong>and</strong> do<br />

something with the response from the <strong>PHP</strong> script on the server.<br />

Working with the Server Response<br />

The getServerTime() function in the preceding section is ready to invoke<br />

theHTTPResponse() <strong>and</strong> do something with the string that is returned.The following<br />

example interprets the response <strong>and</strong> gets a string to display to the end user:<br />

function theHTTPResponse() {<br />

if (myReq.readyState == 4) {<br />

if(myReq.status == 200) {<br />

var timeString =<br />

myReq.responseXML.getElementsByTagName("timestring")[0];<br />

document.getElementById('showtime').innerHTML =<br />

timeString.childNodes[0].nodeValue;<br />

}<br />

} else {<br />

document.getElementById('showtime').innerHTML =<br />

'';<br />

}<br />

}<br />

The outer if…else statement checks the state of the object; if the object is in a state<br />

other than 4 (completed), an animation is displayed ().<br />

However, if myReq is in a readystate of 4, the next check is if the status from the server<br />

is 200 (OK).<br />

If the status is 200, a new variable is created: timeString.This variable is assigned the<br />

value stored in the timestring element of the XML data sent from the server-side script,<br />

which is retrieved by using the getElementByTagname method of the response from the<br />

object:<br />

var timeString = myReq.responseXML.getElementsByTagName("timestring")[0];

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

Saved successfully!

Ooh no, something went wrong!