< Ajax Tutorial

Ajax requests

← Previous Next →


AJAX Requests

The XMLHttpRequest object is used to exchange data with a server.

To send a request to a server, we use the open() and send() methods of the XMLHttpRequest object as:

xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
 Method Description 
 open(method, url, async)  Specifies the type of request

method: the type of request: GET or POST
url: the server (file) location
async: true (asynchronous) or false (synchronous)
 send()  Sends the request to the server (used for GET)
 send(string)  Sends the request to the server (used for POST)

There are two kinds of requests that can be made to the server. They are GET requests and POST requests:

  1. GET Requests

    A simple GET request will be:
    xhttp.open("GET", "demo_get.asp", true);
    xhttp.send(); 

    To avoid a cached result we can add an ID to the URL:

    xhttp.open("GET", "demo_get.asp?t=" + Math.random(), true);
    xhttp.send(); 

    In order to send any information with the GET method, we can add that information to the URL:

    xhttp.open("GET", "demo_get2.asp?fname=Henry&lname=Ford", true);
    xhttp.send(); 

     

  2. POST Requests

    A simple POST request will be:
    xhttp.open("POST", "demo_post.asp", true);
    xhttp.send(); 

    To POST data like an HTML form, add an HTTP header with setRequestHeader(). Specify the data you want to send in the send() method as:

    xhttp.open("POST", "ajax_test.asp", true);
    xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhttp.send("fname=Henry&lname=Ford"); 

     

The onreadystatechange property

With the XMLHttpRequest object we can define a function to be executed when the request receives an answer. The function is defined in the onreadystatechange property of the XMLHttpResponse object. 

The following example shows how to use this property:

xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    document.getElementById("demo").innerHTML = this.responseText;
  }
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send(); 

 

← Previous Next →