Intro
With AJAX you can:
- Update a web page without reloading the page
- Request data from the server AFTER the page has loaded
- Receive data from the server AFTER the page has loaded
- Send data to the server in the BACKGROUND
Used by: Google MAps, Gmail, Youtube, Facebook
How AJAX works
BROWSER
- An event occurs...
- Create an XMLHttpRequest object
- Send HttpRequest
SERVER
- Process HTTPRequest
- Create a response and send data back to the browser
BROWSER
- Process the returned data using JavaScript
- Update page content
Parsing a .txt Document
<script>
// Instantiate a new XMLHttpRequest object
var xhttp = new XMLHttpRequest();
// AJAX event handler
xhttp.onreadystatechange = function() {
if(xhttp.readyState==4 && xhttp.status==200){
// Get the JSON form tthe server and parse it into custs
var custs = JSON.parse(xhttp.responseText);
// Call a function to output the data
outputCustomer(custs);
}
}
// Here's the AJAX open and send calls/functions
// Get ->http Get method
//customers.txt -> file on the server we're getting data from'
// true -> do we want the call to be asynchronous or not?
xhttp.open("GET", "data/XML_10_AJAX_customers.txt", true);
xhttp.send();
// funciotn to output customers
function outputCustomer(custArray){
console.log(custArray);
// var for my output
var output ='';
// Loop through the array and set the output
for(customer of custArray) {
output += "Name: " + customer.Name + "
" + "City: " + customer.City + "
" + "Country: " + customer.Country + "
";
}
document.getElementById("customers").innerHTML = output;
}
</script>