How to Use the XMLHttpRequest Object in JavaScript - dummies

How to Use the XMLHttpRequest Object in JavaScript

By John Paul Mueller

It may at first seem that JavaScript’s XMLHttpRequest object is intensely complicated, but it really isn’t if you take it apart and view it a bit at a time. In reality, most developers use only a few well-known methods and properties. However, it’s entirely possible that developers would use more features of this object if they knew they existed.

How to work with the request

To obtain resources from the server, you must make a request. After all, the server doesn’t read minds. You build up a request by using methods and properties, and then you use the send() method to transmit the request you’ve built. The following list describes the properties normally associated with requests:

  • timeout: Determines the time, in milliseconds, that the request will continue attempting to obtain a required resource from the server.

  • withCredentials: Specifies that the request should include the user’s credentials when set to true. The credentials allow access to secure resources on the server.

  • upload: Provides the server with a XMLHttpRequestUpload object that contains data the server requires to fulfill a request.

Now that you have a better idea of which properties are available to make a request, it’s time to look at the methods. The following methods are usually associated with making a request of some type:

  • open(): Creates a new request. The request can include a number of arguments as defined in the following list in the order you provide them:

    • method: Determines the method used to access the resource. The two valid choices are GET and POST.

    • URL: Specifies the location of the resource on the server.

    • asynchronous: Determines whether the request is made in a synchronous or asynchronous manner. The caller must provide a callback function when this flag is set to true (for an asynchronous request).

    • username: Contains the user’s logon name for secure resource access.

    • password: Contains the user’s password for secure resource access.

  • setRequestHeader(): Creates a name/value pair to include with the request header. You supply the name and value as two separate arguments that the call uses to create the request header entry.

  • send(): Transmits the request to the server. It sounds simple, but a number of features are in place to make the process more reliable. You can read about the entire process. However, from a developer’s perspective, how send() works isn’t nearly as important as what send() returns. The send() method either returns data or an error. Here are the four most common errors:

    • network: Something has happened to stop the request from reaching the server. In some cases, a Domain Name System (DNS) error causes the request to get lost before it reaches the server. In other cases, a Transport Layer Security (TLS) error occurs, which means that your application may not have the required credentials.

    • abort: The end user has cancelled the request. To cause this error, your application must call the abort() method.

    • timeout: A request has wandered about looking for the resource it needs and finally given up. Requests have a timeout value associated with them. Otherwise, the request could continue looking for a resource indefinitely if that resource doesn’t exist.

    • request: There’s a problem with the request. You normally have to dig deeper to find out precisely what the problem is. However, there are a number of common causes, including: requesting a non-existent resource, not providing a required argument, and providing information of the wrong type.

  • abort(): Stops execution of the current request.

How to work with the response

The XMLHttpRequest object also provides a number of response properties and methods that you use to determine the success or failure of a request. Here are the properties that you commonly use when working with this object:

  • status: Returns the HTTP status code. A status code of 200 means that the request completed successfully. Any other code normally reflects some sort of problem with the request process. Here is a list of status codes.

  • statusText: Returns the HTTP status as a textual value. For example, a status code of 200 returns a text value of OK. Here is a list of status text values and their associated codes.

  • readyState: Specifies the current state of asynchronous processing. The state can be any of these values:

    • 0: Request not initialized

    • 1: Server connection established

    • 2: Request received

    • 3: Processing request

    • 4: Request finished and response is ready

  • responseType: Returns the value of the Content-Type response header. An application can use this value to determine how to react to the type of response the server has sent. The common return types are

    • : An empty string indicates that the return type is unknown or that an error has occurred and there’s no response to process.

    • arraybuffer: The data is in the form of an array.

    • blob: The sender has used a Binary Large Object (BLOB) to store the data.

    • document: The data appears as structured information in an XML document. Normally, the document is complete, rather than an XML fragment.

    • json: The sender has used JavaScript Object Notation (JSON) to encapsulate the data.

    • text: The information appears as plain text, which may mean that it lacks context and structure. However, some text formats are structured, such as Comma Separated Variable (CSV).

  • response: Contains the entire response without any interpretation as an object.

  • responseText: Contains only the text of a response when the responseType value is (the empty string) or text. This property returns nothing for other responseType values.

  • responseXML: Contains only the XML document when the responseType value is (the empty string) or document. This property returns nothing for other responseType values.

The response methods help you interact with the response data in some way. Here are the response methods:

  • getResponseHeader(): Obtains a specific response header value from the response object. You supply the value of the response header you want, such as Content-Type, as an argument to the method. There are no required response headers, and a server can create custom headers.

  • getAllResponseHeaders(): Creates an array of all of the response headers except those that are listed as Set-Cookie or Set-Cookie2.

  • overrideMimeType(): Specifies the value of the Content-Type response header.