Asynchronous JavaScript and XML


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

  1. An event occurs...
  2. Create an XMLHttpRequest object
  3. Send HttpRequest

SERVER

  1. Process HTTPRequest
  2. Create a response and send data back to the browser

BROWSER

  1. Process the returned data using JavaScript
  2. 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>

CUSTOMERS