AJAX Introduction
AJAX is like a dream for developers, as it allows them to:
- Retrieve information from a web server - once the webpage has finished loading.
- Refresh a webpage without having to reload it.
- Transmit information to a web server without disrupting the foreground.
AJAX Example Explained
HTML Page
<!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>
The webpage has a <div> section and a <button>.
The <div> part is utilized to show data received from a server.
The <button> triggers a function when clicked.
The function asks a web server for information and shows it.
Function loadDoc()
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 AndXML.
AJAX isn't a language for programming.
AJAX works by using a mix of:
- A browser has a built-in tool called
XMLHttpRequest
to ask a web server for information. - Using JavaScript and HTML DOM to show or utilize data.
The name AJAX is kind of misleading. When we talk about AJAX applications, they can use XML to move data around, but they often use plain text or JSON instead.
AJAX helps web pages change without refreshing the entire page. It works by swapping data with a web server quietly in the background. This way, sections of a web page can be refreshed without needing to reload the entire page.
How AJAX Works
- 1. Something happens on a webpage (like when it loads or when a button gets clicked).
- 2. JavaScript makes an object called XMLHttpRequest.
- 3. The XMLHttpRequest object asks a web server for something.
- 4. The server handles the request.
- 5. The server sends information back to the webpage.
- 6. JavaScript reads the response.
- 7. JavaScript does the right things, like updating a page.
Modern Browsers (Fetch API)
Newer web browsers can utilize the Fetch API in place of the XMLHttpRequest Object.
The Fetch API lets web browsers ask web servers for information using HTTP requests.
If you're using the XMLHttpRequest Object, Fetch does the same thing but in a simpler manner.