AJAX Module
AJAX Module
What is AJAX?
A browser built-in XMLHttpRequest object (to request data from a web server)
JavaScript and HTML DOM (to display or use the data)
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.
AJAX allows web pages to be updated asynchronously by exchanging 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.
Method Description
Property Description
To send a request to a server, we use the open() and send() methods of the XMLHttpRequest
object:
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
Method Description
GET or POST?
GET is simpler and faster than POST, and can be used in most cases.
However, always use POST requests when:
By sending asynchronously, the JavaScript does not have to wait for the server response, but can
instead:
With the XMLHttpRequest object you 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:
Property Description
<!DOCTYPE html>
<html>
<body>
<div id="demo">
<h2>The XMLHttpRequest Object</h2>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>
<script>
function loadDoc() {
var 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", true);
xhttp.send();
}
</script>
</body>
</html>
Output
The XMLHttpRequest Object
Change Content
ajax_info.txt