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.

Chapter 2<br />

Figure 2.6: The Four HTTP Request Status Codes<br />

Don't worry if your browser doesn't display exactly the same message. Some<br />

XMLHttpRequest implementations simply ignore some status codes. Opera, for example,<br />

will only fire the event for status codes 3 <strong>and</strong> 4. Internet Explorer will report status codes<br />

2, 3, <strong>and</strong> 4 when using a more recent XMLHttp version.<br />

What Just Happened?<br />

To underst<strong>and</strong> the exact flow of execution, let's start from where the processing begins—the<br />

async.html file:<br />

<br />

<br />

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

<br />

<br />

<br />

This bit of code hides some interesting functionality. First, it references the async.js file, the<br />

moment at which the code in that file is parsed. Note that the code residing in JavaScript functions<br />

does not execute automatically, but the rest of the code does. All the code in our JavaScript file is<br />

packaged as functions, except one line:<br />

// holds an instance of XMLHttpRequest<br />

var xmlHttp = createXmlHttpRequestObject();<br />

This way we ensure that the xmlHttp variable contains an XMLHttpRequest instance right from the<br />

start. The XMLHttpRequest instance is created by calling the createXmlHttpRequestObject<br />

function that you encountered a bit earlier.<br />

The process() method gets executed when the onload event fires. The process() method can<br />

rely on the xmlHttp object being already initialized, so it only focuses on initializing a server<br />

request. The proper error-h<strong>and</strong>ling sequence is used to guard against potential problems. The code<br />

that initiates the server request is:<br />

// initiate reading the async.txt file from the server<br />

xmlHttp.open("GET", "async.txt", true);<br />

53<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!