XML HttpRequest
- Previous Page XML Display
- Next Page XML Parser
All modern browsers have built-in XMLHttpRequest objects for requesting data from servers.
XMLHttpRequest object
The XMLHttpRequest object can be used to request data from a web server.
The XMLHttpRequest object isDevelopers' DreamBecause you can:
- Updating the web page - without reloading the page
- Requesting data from the server - after the page has loaded
- Receiving data from the server - after the page has loaded
- Sending data to the server - in the background
XMLHttpRequest instance
When you type characters in the input field below, an XMLHttpRequest will be sent to the server, and some name suggestions (from the server) will be returned:
Example
Please enter your name in the input field below:
Name: Suggestions: The AJAX chapter of this tutorial explains the above example.Sending an XMLHttpRequest
The following is the common JavaScript syntax used with the XMLHttpRequest object:
Example
var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { // Typical action to be performed when the document is ready: document.getElementById("demo").innerHTML = xhttp.responseText; } }; xhttp.open("GET", "filename", true); xhttp.send();
Example Explanation
The first line in the above example creates a XMLHttpRequest object:
var xhttp = new XMLHttpRequest();
onreadystatechange
The property specifies the function to be executed each time the state of the XMLHttpRequest object changes:
xhttp.onreadystatechange = function()
When readyState
The property is 4 and status
When the property is 200, the response is ready:
if (this.readyState == 4 && this.status == 200)
responseText
Attributes are returned as text strings from the server response.
Text strings can be used to update the web page:
document.getElementById("demo").innerHTML = xhttp.responseText;
You will learn more about the XMLHttpRequest object in the AJAX chapter of this tutorial.
- Previous Page XML Display
- Next Page XML Parser