HTTP Requests - Java Script

In many modern browsers,it’s possible to initiate HTTP requests directly from JavaScript and get the result back in JavaScript,completely eliminating the need for hidden frames and other such trickery.

At the center of this exciting new capability is an object Microsoft created called the XML HTTP request. This object came along with MSXML but wasn’t fully explored until recently.Essentially, an XML HTTP request is a regular HTTP request with added functionality for sending and receiving XML code.

To create a new XML HTTP request in Internet Explorer,you must once again use an ActiveXObject:

var oRequest = new ActiveXObject(“Microsoft.XMLHTTP”);

Like the XML DOM in IE,the XML HTTP request object has multiple versions,so a function is necessary to make sure you’re using the most recent one:

After you have created it,you can use the open() method to specify the request to send.This method takes three arguments:the type of request to send (GET, POST, or any other HTTP method supported by the server);the URL of the request; and a Boolean indicating whether the request should be sent asynchronously or not(the same as you do with the XML DOM load() method).For example:

oRequest.open(“get”,“example.txt”, false);

After opening the request, you must send it by using the send() method.This method always requires an argument, which can be null most of the time:

oRequest.send(null);

If you choose to make the request synchronously (setting the third argument to false),the JavaScript interpreter waits for the request to return.When the response comes back,it fills the status property with the HTTP status of the request(200 is good, 404 means the page wasn’t found, and so on).It also fills the statusText property with a message describing the status and the responseText property with the text received back from the server. Additionally,if the text is XML,it fills the responseXML property, which is an XML DOM object constructed from the returned text.For example:

This example gets a plain text file and displays its contents.The status and statusText are also displayed. Requesting an XML file also fills the responseXML property:

This example shows the tag name of the document element loaded into the responseXML property.If you decide to send an asynchronous request, you must use the onreadystatechange event handler to see when the readyState property is equal to 4 (the same as with the XML DOM). All the same properties and methods are used,with the slight alteration that the response properties can’t be used until the request has completed:

As in the synchronous calls, the status, statusText,and responseText properties are filled with data.

With asynchronous calls,it’s possible to cancel the request altogether by calling the abort() method before the readyState reaches 4:

In this example,the alerts are never displayed because the request is aborted when readyState is 3.

Using headers

Every HTTP request sends along with it a group of headers with additional information.In everyday browser use, these headers are hidden because they aren’t needed by the end user.However, these headers can be quite necessary to developers,and so the XML HTTP request object provides methods to get and set them.

The first is a method called getAllResponseHeaders(), which returns a string containing all the headers attached to the response.Here’s a sample of the type of information returned by getAllResponseHeaders():

From this header information, you can tell that the server is running Apache on Unix with PHP support and the file being returned is an HTML file.If you want to retrieve only one of the headers, you can use the getResponseHeader() method with the name of header to retrieve. For example,to retrieve the value of the “Server” header, you can do this:

var sValue = oRequest.getResponseHeader(“Server”);

Reading request headers is just part of the equation; the other part is setting your own headers on the request before it’s sent. Using the setRequestHeader() method,you can set headers on the XML HTTP request before it’s sent out. For example:

Assuming that you have some server-side logic designed to take these headers into account, you can provide some additional functionality and/or evaluation of requests.

Copycat implementations

This object proved to be so popular among Web developers that other browser makers copied the implementation. Mozilla was the first of the copycats, creating a JavaScript object called XMLHttpRequest that behaves exactly the same as Microsoft’s version. Both Safari (as of 1.2) and Opera (as of 7.6) copied Mozilla’s implementation,creating their own XMLHttpRequest objects.

To allow creation of an XML HTTP request in a common way,just add this simple wrapper class to your pages:

This code allows you to use the following line to create an XML HTTP request in all browsers that support it:

var oRequest = new XMLHttpRequest();

After this point,the XML HTTP request can be used in all supporting browsers as described in the previous sections.

Performing a GET request

The most common type of request on the Web is a GET request.Every time you enter a URL into your browser and click Go, you are sending a GET request to a server.

Parameters to a GET request are attached to the end of the URL with a question mark, followed by name/value pairs separated by an ampersand.

Each name and value must be encoded for use in a URL (in JavaScript,this can be done using encodeURIComponent()). The URL has a maximum size of 2048 characters (2 MB).Everything after the question mark is referred to as the query string, and these parameters are accessible by server-side pages.

To send a GET request using the XML HTTP request object, just place the URL (with all parameters) into the open() method and make sure this first argument is “get”:

oRequest.open(“get”,“http://www.somewhere.com/page.php?name1=value1”, false);

Because the parameters must be added to the end of an existing URL, it’s helpful to have a function that handles all the details:

The addURLParam() function takes three arguments: the URL to add the parameters to, the parameter name, and the parameter value. First, the function checks to see if the URL already contains a question mark (to determine if other parameters already exist). If it doesn’t,then the function appends a question mark; otherwise, it adds an ampersand. Next, the name and value are encoded and appended to the end of the URL.The last step is to return the updated URL.

This function can be used to build up a URL for a request:

You can then handle the response as usual.

Performing a POST request

The second most common type of HTTP request is a POST. Typically,POST requests are used whennentering data into a Web form because they are capable of sending much more data (around 2 GB) than GET requests.

Just like a GET request, the parameters for a POST request must be encoded for use in a URL and separated with an ampersand, although the parameters aren’t attached to the URL. When sending a POST request, you pass in the parameters as an argument to the send() method:

It also helps to have a function for formatting the parameters for a POST request:

This function is similar to the addURLParam() function, although addPostParam() deals with a string of parameters instead of a URL. The first argument is the existing list of parameters,the second argument is the parameter name, and the third is the parameter value. he function checks whether the length of the parameters string is longer than 0. If so, then it adds an ampersand to separate the new parameter.Otherwise,it returns the parameter string with the new name and value added.Here’s a brief example of its use:

Even though this looks like a valid POST request, a server-side page expecting a POST actually won’t interpret this code correctly. That’s because all POST requests sent by a browser have the “Content- Type” header set to “application / x-www-form-urlencoded”. Fortunately, that can be easily corrected using the setRequestHeader() method:

Now this example works just like a form POSTed from a Web browser.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Java Script Topics