DONATE  
MENU
JAVASCRIPT
JSON
AJAX
HTML

AJAX Tutorials

JAVASCRIPT AJAX

» Introduction

» HTTP Request Object

» AJAX Example

» AJAX GET Request

» AJAX POST Request

.. » AJAX » Javascript Ajax » HTTP Request Object
Share Tweet WhatsApp

HTTP Request Object

To help understand how to start sending HTTP requests to your webpage server, let's examine the HTTP request Object, its properties and methods. The HTTP request Object enables us to send requests to files on a server. We start by creating a new copy of the object from its prototype on a variable as shown below,
var http = new XMLHttpRequest();
With the new object variable (http or whatever name) created, you can thereafter call on its various methods to send a request while its properties or values mainly help in knowing what the status of our request, the server responses and feedbacks are. NOTE: Some versions of Internet Explorer(a browser) do not support the above XMLHttpRequest() object. To solve this, we use the below object for such browsers:
var http = new ActiveXObject("Microsoft.XMLHTTP");
We can combine both to have cross browser support or full support on all browsers:
var http;
//CHECK IF BROWSER SUPPORTS XMLHttpRequest
if (XMLHttpRequest){
//it is supported
http = new XMLHttpRequest();
}
else
{
//Not supported. Use ActiveXObject
http = new ActiveXObject("Microsoft.XMLHTTP");
}
//You are good to go
Both the XMLHttpRequest() and the ActiveXObject("Microsoft.XMLHTTP") have the same definitions. That is, they contain the same properties and methods. Just different prototype name. HTTP REQUEST OBJECT PROPERTIES Below are some of the properties of the HTTP request object. They mainly help us in monitoring the status of our request and in getting whatever was returned by the server. To fully achieve this, most of their values change in response to the request processing.
PROPERTY NAMEPOSSIBLE VALUEDESCRIPTION
onreadystatechangefunction definitiionA function to call when request state or readyState changes.
readyState0 1 2 3 4Returns the state of the request. it is 0 when request has not started. Changes to 1 when connection to server is established. Changes to 2 when request is recieved. Changes to 3 when request is processed. Changes to 4 when request is ready.
responseTextstringReturns whatever data that was contained in the file a request was sent to in text format.
responseXMLXMLReturns whatever data that was contained in the file a request was sent to in XML format.
status200 403 404Returns the status of the request. 200 if request was OK. 403 if request was forbidden. 404 if file was not found.
statusTextOK Not Found Returns a text as regard the status of the request. "OK" if successful else "Not Found".
HTTP REQUEST OBJECT METHODS 1. open() The HTTP request open() method is used in opening the request or getting it ready. It has three parameters giving details about the request which are:
  1. THE REQUEST METHOD: This can be POST or GET.
  2. THE FILE: The path or URL to the file a request is being sent to. if request method is GET and we want to send values with the request, we should append such values to the URL e.g myfile.php?num1=2&num2=5&num3=1 where my file.php is the filepath, num1 is a parameter or variable with value of 2 and so on.
  3. THE SYNC METHOD: This can be true or false. If set to true, it means the request should be sent asynchronously. That is, other executions on a webpage should continue whether request is finished or not. If false, it means other executions on the webpage should wait till request is complete or finished(synchronously).
http.open(method, file, sync);
http.open("GET","myfile.txt", true); //Asynchronous request
http.open("POST","myfile.txt", false); //Synchronous Request
2. send() The send() method is used in sending the request. If the request method is POST and there are any values to send along with the request, you specify such as its parameter.
http.send(); //No value sent
http.send("name=Omamode");//Sending a value for a POST request
http.send("name=Omamode&age=44&adult="+true);//Sending values for a POST request

var name = "Omamode";
var age = 44;
var adult_status = true;
http.send("name="+name+"&age="+age+"&adult="adult_status);//Sending values in variables for a POST request
Notice from the above how the value_name=value pairs were separated with the ampersand (&) symbol. Each value_name is called a parameter and the value is the parameter value. 3. setRequestHeader() The setRequestHeader() is used in specifying a header for the request body. This method is particularly necessary when such a request method is POST.
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
PROCEDURE IN SENDING HTTP REQUEST WITH THE PROPERTIES AND METHODS
  1. Create HTTP request Object.
    var http;
    //KNOW IF BROWSER SUPPORTS XMLHttpRequest
    if (XMLHttpRequest){
    //it is supported
    http = new XMLHttpRequest();
    }
    else
    {
    //Not supported. Use ActiveXObject
    http = new ActiveXObject("Microsoft.XMLHTTP");
    }
    //You are good to go
  2. Open request with open() method.
    http.open("POST","myfile.php",true);
  3. Set request headers if request method is POST.
    http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
  4. Send request with send() method.
    http.send("name=Omamode");
  5. Know if request was successful or not using the various properties.
    http.onreadystatechange = /* function to call when request state changes */
    function (){
    if (this.readyState == 4 /*If request is ready */ && this.status == 200 /*if request was successful*/){
    var response = this.responseText; //Content of the file in text format
    var responseXML = this.responseXML; //Content of the file in XML format
    //You can then do anything with the responseText or responseXML e.g
    alert(response);
    }
    };
COMPLETE CODE
var http;
if (XMLHttpRequest){
http = new XMLHttpRequest();
}
else
{
http = new ActiveXObject("Microsoft.XMLHTTP");
}

http.open("POST","myfile.php",true);

http.setRequestHeader("Content-type","application/x-www-form-urlencoded");

http.send("name=Omamode");

http.onreadystatechange = function (){
if (this.readyState == 4  && this.status == 200){
alert(this.responseText);
}
};
SUMMARY
  1. AJAX requests are sent using the XMLHttpRequest() Object.
  2. Some browsers like old versions of Internet Explorer do not support the XMLHttpRequest() Object. Alternatively, we can use the ActiveXObject("Microsoft.XMLHTTP").
  3. Both the XMLHttp and the ActiveXObject have same properties and methods. The prototype name is the difference.
  4. We can declare a variable and then check if a browser supports the XMLHttpRequest else we create a copy of the ActiveXObject.
  5. The methods of the request objects which include open(), send(), setRequestHeader() perform actions to send the request. The properties or values on the other hand contain values that helps us determine the state and status of the request including what was the server response is.
  6. Sending a request begins with creating a new copy of the HTTP request object, calling its open() method to prepare the request body, setting request headers with the setRequestHeader() and finally sending the request with the send() method. We thereafter assign a function definition to the onreadystatechange property to handle how our request is fairing or faired.
  7. Inside the function definition, we should check if our request is ready (readyState == 4) and if our request status is okay (status == 200). If this is true, then, we can do whatever we want with the text or XML response from the file the request was sent to.
Take a short quiz on HTTP Request Object.
Ask a question or tell us if HTTP Request Object is easy or not.
cent?

Join our 1,090 subscribers to receive tutorials' updates!

  We won't spam your mail box. We hate it.





StackBeginner 2021 © Joseph Omamode