AJAX - Request
To initiate an HTTP request, we need to create a new XMLHttpRequest object.
var xhttp = new XMLHttpRequest();
Older versions of Internet Explorer (Prior to 6) don't offer support to the XMLHttpRequest object, therefore to ensure compatibility we can use a ternary of and include a fallback to Microsoft's ActiveXObject:
var xhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
This object will be responsible for doing the HTTP request. When this is done it's important to know the states of an HTTP request:
| State | Description |
|---|---|
| 0 | Request initialized |
| 1 | Connection to the server established |
| 2 | Request received |
| 3 | Processing request |
| 4 | Response received and request finalized |
The state that is interesting to us is 4, which is when we receive the response back. Besides the state we also need to pay attention to the status of the request to make sure it is not an error. The table below shows the most common status codes:
| Status | Description |
|---|---|
| 200 | OK - Response received successfully |
| 403 | Not authorized |
| 404 | Not found |
Now we need to create a function that will use basically 4 properties of the XMLHttpRequest object:
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
};
Let's now send our first HTTP request to Open Trivia, a database of trivia questions. In the next project we will use it to create an interactive quiz game.
The open method will be used to start the request. In this method we need two arguments:
xhttp.open("GET", "https://opentdb.com/api.php?amount=1");
xhttp.send();
If all went well we now should be viewing the response. In the next lesson we'll learn how to work with it.