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.

Fundamental Ajax<br />

861<br />

Note<br />

For security reasons, the XMLHTTPRequest object can call URLs only within the same domain; it cannot<br />

directly call a remote server.<br />

The XMLHTTPRequest object is often referred to as the “guts” of any Ajax application<br />

given that it is the gateway between the client request <strong>and</strong> the server response. Although<br />

you will soon learn the basics of creating <strong>and</strong> using an instance of the XMLHTTPRequest<br />

object, see http://www.w3.org/TR/XMLHttpRequest/ for a more detailed underst<strong>and</strong>ing.<br />

The XMLHTTPRequest object has several attributes, as shown in Table 34.1.<br />

Table 34.1 Attributes of the XMLHTTPRequest Object<br />

Attribute<br />

Description<br />

onreadystatechange Specifies the function that should be invoked when the<br />

readyState property changes.<br />

readyState<br />

The state of the of request, represented by integers 0 (uninitialized),<br />

1 (loading), 2 (loaded), 3 (interactive), <strong>and</strong> 4 (completed).<br />

responseText Contains data returned as a string of characters.<br />

responseXml Contains data returned as an XML-formatted document object.<br />

status An HTTP status code returned by the server, such as 200.<br />

statusText<br />

An HTTP status phrase returned by the server, such as OK.<br />

The XMLHTTPRequest object has several methods, as shown in Table 34.2.<br />

Table 34.2 Methods of the XMLHTTPRequest Object<br />

Method<br />

Description<br />

abort()<br />

Stops the request.<br />

getAllResponseHeaders() Returns all the headers in the response as a string.<br />

getResponseHeader(header) Returns the value of header header as a string.<br />

open('method', 'URL', 'a') Specifies the HTTP method method (such as POST or<br />

GET), the target URL URL, <strong>and</strong> whether the request<br />

should be asynchronous (where a is ‘true’) or not (where a<br />

is false).<br />

send(content)<br />

Sends the request, with optional POST content content.<br />

setRequestHeader('x', 'y') Sets a parameter (x) <strong>and</strong> value (y) pair <strong>and</strong> sends it as a<br />

header with the request.<br />

Before using the functionality of XMLHTTPRequest, you must first create an instance of it.<br />

This necessitates a bit more than simply typing<br />

var request = new XMLHTTPRequest();

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

Saved successfully!

Ooh no, something went wrong!