Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1
CHAPTER 18 ■ AJAX AND JSON^279

all modern browsers. The script in Listing 18-5 will try the modern route first and will fall back
to the ActiveX method if the native XHR object is not available.
Tables 18-1 and 18-2 describe the properties and methods available to the XHR object.

Table 18-1. XmlHttpRequest Methods
Method Description
abort() Cancels an in-progress request.
getAllResponseHeaders() Gets all the response headers as a string.
getResponseHeader(name) Gets a specific header by name.
open(method, url [, async, user, pass]) Creates a new HTTP connection. The method
may be any valid request type like GET or POST.
The URL should be a fully qualified address.
The async method controls whether the send()
method will block (wait for data to come back
from the server) or return immediately. The
user and pass parameters are used if the server
resource requires HTTP authentication.
send(content) Invokes the request to the server. It uses the
settings provided to open() and will either return
immediately or wait for content to be received
from the server based on the open() method’s
async parameter. The content parameter is used
with certain types of requests, like POST to send
data to the server.
setRequestHeader(name, value) Sets a request header by name and value.

Table 18-2. XmlHttpRequest Properties
Property Description
readyState Indicates the current state of the XHR object. It returns a numeric representa-
tion of the state, where 0 = uninitialized, 1 = open, 2 = sent, 3 = receiving, 4 =
loaded. This property is most commonly used when working asynchro-
nously. In this case, you should check that readyState equals 4 when the
onreadystatechange event fires. The onreadystatechange event is fired
whenever there is a change to the readystate property of the object. Most
commonly, this is used to discover when the response from the server is
complete. Check the readyState property when the onreadystatechange
event fires to determine the new state.
responseText The response from the server as a string.
responseXML The response from the server represented as a DOM XML object.
status The HTTP status code of the response ( 200 , 404 , and so on).
statusText A string representation of the status code ('OK', 'NOT FOUND', and so on).

McArthur_819-9.book Page 279 Friday, February 29, 2008 8:03 AM

Free download pdf