What is AJAX
AJAX stands for Asynchronous JavaScript and XML.
Asynchronous means requests are sent without stopping or waiting for a response, your app will keep running.
XML is the format that server responses were sent in.
What is one characteristic of "asynchronous" AJAX requests?
Callbacks for multiple AJAX requests may not run in the order the requests were sent.
AJAX lets you update HTML without loading a new webpage.
Update content on a web page without loading a new web page.
AJAX works with server-side languages such as Ruby, PHP, Python, Cold Fusion, and many others.
AJAX lets you build you web pages that ask for information from a web server.
The web server returns data to the web browser, and JavaScript processes that data to selectively change parts of the web page.
Put simply, AJAX is the process of using JavaScript to send a request to a web server, and receive a response back, and then do something with that response.
How AJAX Works
- Create XMLHttpRequest Object
- Open request
- Create callback function
- Send request
You can break the AJAX programming process into four steps.
1. Create XMLHTTP Request Object
This step tells the web browser to get ready. The web browser needs to create a JavaScript object –XHR object– that has all the methods you’ll need to send a request and receive data.
var xhr = new XMLHttpRequest();
2. Open Request
Give the browser two pieces of information: 1. The method the browser will use to send the request (e.g. GET or POST), 2. The URL where the request is sent.
xhr.open('GET', 'sidebar.html');
3. Define Callback Function
The callback will be where you process the returned data and update the HTML on the page.
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
document.getElementById('ajax').innerHTML = xhr.responseText;
}
};
4. Send Request!
xhr.send();
Example
sidebar.html
<section>
<h2>Welcome to the wonderful world of AJAX</h2>
<p>This content provided to you dynamically by the XMLHTTP Request Object</p>
</section>
index.html
<!DOCTYPE html>
<html>
<head>...</head>
<body>
<h1>Bring on the AJAX</h1>
<button id="load" onclick="sendAJAX()" class="button">Bring it!</button>
<ul id="ajax">
</ul>
<script>
var xhr = new XMLHttpRequest();
xhr.open('GET', 'sidebar.html');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if( xhr.status === 200) {
document.getElementById('ajax').innerHTML = xhr.responseText;
} else if( xhr.status === 404) {
//file not found
} else if( xhr.status === 500) {
//server error
} else {
alert(xhr.statusText);
}
}
};
function sendAJAX() {
xhr.send();
document.getElementById('load').style.display = 'none';
}
</script>
</body>
</html>