Ajax Notes
Ajax Notes
Read data from a web server - after the page has loaded
Update a web page without reloading the page
Send data to a web server - in the background
<!DOCTYPE html>
<html>
<body>
<div id="demo">
</div>
<script>
function loadDoc() {
xhttp.onload = function() {
document.getElementById("demo").innerHTML =
this.responseText;
xhttp.open("GET", "ajax_info.txt");
xhttp.send();
</script>
</body>
</html>
Output -:
What is AJAX?
AJAX = Asynchronous JavaScript And XML.
AJAX is a misleading name. AJAX applications might use XML to transport data,
but it is equally common to transport data as plain text or JSON text.
The Fetch API interface allows web browser to make HTTP requests to web
servers.
If you use the XMLHttpRequest Object, Fetch can do the same in a simpler way.
AJAX - The XMLHttpRequest
Object
❮ PreviousNext ❯
The XMLHttpRequest object can be used to exchange data with a web server
behind the scenes. This means that it is possible to update parts of a web page,
without reloading the whole page.
xhttp.onload = function() {
// What to do when the response is ready
}
Send a Request
To send a request to a server, you can use the open() and send() methods of
the XMLHttpRequest object:
xhttp.open("GET", "ajax_info.txt");
xhttp.send();
Example
// Create an XMLHttpRequest object
const xhttp = new XMLHttpRequest();
// Send a request
xhttp.open("GET", "ajax_info.txt");
xhttp.send();
Try it Yourself »
This means that both the web page and the XML file it tries to load, must be
located on the same server.
The examples on W3Schools all open XML files located on the W3Schools
domain.
If you want to use the example above on one of your own web pages, the XML
files you load must be located on your own server.
ADVERTISEMENT
Example
xhttp.onload = function() {
document.getElementById("demo").innerHTML = this.responseText;
}
xhttp.open("GET", "ajax_info.txt");
xhttp.send();
Try it Yourself »
Multiple Callback Functions
If you have more than one AJAX task in a website, you should create one
function for executing the XMLHttpRequest object, and one callback function for
each AJAX task.
The function call should contain the URL and what function to call when the
response is ready.
Example
loadDoc("url-1", myFunction1);
loadDoc("url-2", myFunction2);
function myFunction1(xhttp) {
// action goes here
}
function myFunction2(xhttp) {
// action goes here
}
Property Description
Example
function loadDoc() {
const xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt");
xhttp.send();
}
Try it Yourself »
The onreadystatechange event is triggered four times (1-4), one time for each
change in the readyState.
AJAX - XMLHttpRequest
❮ PreviousNext ❯
Method Description
open(method, url, async) Specifies the type of request
The file can be any kind of file, like .txt and .xml, or server scripting files like
.asp and .php (which can perform actions on the server before sending the
response back).
By sending asynchronously, the JavaScript does not have to wait for the server
response, but can instead:
execute other scripts while waiting for server response
deal with the response after the response is ready
You can safely remove the third parameter from your code.
GET or POST?
GET is simpler and faster than POST, and can be used in most cases.
GET Requests
A simple GET request:
Example
xhttp.open("GET", "demo_get.asp");
xhttp.send();
Try it Yourself »
In the example above, you may get a cached result. To avoid this, add a unique
ID to the URL:
Example
xhttp.open("GET", "demo_get.asp?t=" + Math.random());
xhttp.send();
Try it Yourself »
If you want to send information with the GET method, add the information to the
URL:
Example
xhttp.open("GET", "demo_get2.asp?fname=Henry&lname=Ford");
xhttp.send();
Try it Yourself »
How the server uses the input and how the server responds to a request, is
explained in a later chapter.
POST Requests
A simple POST request:
Example
xhttp.open("POST", "demo_post.asp");
xhttp.send();
Try it Yourself »
To POST data like an HTML form, add an HTTP header with setRequestHeader().
Specify the data you want to send in the send() method:
Example
xhttp.open("POST", "ajax_test.asp");
xhttp.setRequestHeader("Content-type", "application/x-www-form-
urlencoded");
xhttp.send("fname=Henry&lname=Ford");
Try it Yourself »
Method Description
Synchronous Request
To execute a synchronous request, change the third parameter in
the open() method to false:
Sometimes async = false are used for quick testing. You will also find
synchronous requests in older JavaScript code.
Since the code will wait for server completion, there is no need for
an onreadystatechange function:
Example
xhttp.open("GET", "ajax_info.txt", false);
xhttp.send();
document.getElementById("demo").innerHTML = xhttp.responseText;
Try it Yourself »
Example
document.getElementById("demo").innerHTML = xhttp.responseText;
Try it Yourself »
The responseXML Property
The XMLHttpRequest object has an in-built XML parser.
The responseXML property returns the server response as an XML DOM object.
Using this property you can parse the response as an XML DOM object:
Example
Request the file cd_catalog.xml and parse the response:
xhttp.open("GET", "cd_catalog.xml");
xhttp.send();
Try it Yourself »
ADVERTISEMENT
getAllResponseHeaders() Returns all the header information from the server resource
Example
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
document.getElementById("demo").innerHTML =
this.getAllResponseHeaders();
}
xhttp.open("GET", "ajax_info.txt");
xhttp.send();
Try it Yourself »
Example
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
document.getElementById("demo").innerHTML =
this.getResponseHeader("Last-Modified");
}
xhttp.open("GET", "ajax_info.txt");
xhttp.send();
Try it Yourself »