27.10.2015 Views

AJAX and PHP

Create successful ePaper yourself

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

Chapter 2<br />

The safer version of process() looks like that:<br />

// called to read a file from the server<br />

function process()<br />

{<br />

// only continue if xmlHttp isn't void<br />

}<br />

if (xmlHttp)<br />

{<br />

// try to connect to the server<br />

}<br />

try<br />

{<br />

// initiate reading the a file from the server<br />

xmlHttp.open("GET", "server_script.php", true);<br />

xmlHttp.onreadystatechange = h<strong>and</strong>leRequestStateChange;<br />

xmlHttp.send(null);<br />

}<br />

// display the error in case of failure<br />

catch (e)<br />

{<br />

alert("Can't connect to server:\n" + e.toString());<br />

}<br />

If xmlHttp is null (or false) we don't display yet another message, as we assume a message was<br />

already displayed by the createXmlHttpRequestObject function. We make sure to display any<br />

other connection problems though.<br />

H<strong>and</strong>ling Server Response<br />

When making an asynchronous request (such as in the code snippets presented earlier), the<br />

execution of xmlHttp.send() doesn't freeze until the server response is received; instead, the<br />

execution continues normally. The h<strong>and</strong>leRequestStateChange method is the callback method<br />

that we set to h<strong>and</strong>le request state changes. Usually this is called four times, for each time the<br />

request enters a new stage. Remember the readyState property can be any of the following:<br />

0 = uninitialized<br />

1 = loading<br />

2 = loaded<br />

3 = interactive<br />

4 = complete<br />

Except state 3, all the others are pretty self-explaining names. The interactive state is an<br />

intermediate state when the response has been partially received. In our <strong>AJAX</strong> applications we<br />

will only use the complete state, which marks that a response has been received from the server.<br />

The typical implementation of h<strong>and</strong>leRequestStateChange is shown in the following code<br />

snippet, which highlights the portion where you actually get to read the response from the server:<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 />

// retrieve the response<br />

response = xmlHttp.responseText;<br />

49<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!