unit 2 AJAX
unit 2 AJAX
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">
<h2>Let AJAX change this text</h2>
<button type="button" onclick="loadDoc()">Change
Content</button>
</div>
</body>
</html>
function loadDoc() {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
document.getElementById("demo").innerHTML = this.responseText;
}
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
what is AJAX?
AJAX = Asynchronous JavaScript And XML.
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.
Create an XMLHttpRequest Object
All modern browsers (Chrome, Firefox, IE, Edge, Safari, Opera) have a built-
in XMLHttpRequest object.
In this case, the callback function should contain the code to execute when
the response is ready.
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();
<!DOCTYPE html>
<html>
<body>
<div id="demo">
<p>Let AJAX change this text.</p>
</div>
<script>
function loadDoc() {
xhttp.onload = function() {
document.getElementById("demo").innerHTML = this.responseText;
xhttp.open("GET", "ajax_info.txt");
xhttp.send();
</script>
</body>
</html>
Method Description
The status property and the statusText properties hold the status of the
XMLHttpRequest object.
Property Description
<!DOCTYPE html>
<html>
<body>
<div id="demo">
</div>
<script>
function loadDoc() {
xhttp.onreadystatechange = function() {
document.getElementById("demo").innerHTML =
this.responseText;
};
xhttp.open("GET", "ajax_info.txt");
xhttp.send();
</script>
</body>
</html>