Ajax

Dynamically accessing data

Asynchronous Javascript and XML

AJAX is a really useful tool that allows you to query a data source and dynamically update it on your page without having to reload. This is imperative for optimal interaction with your user (remember what can happen to our JS when the page reloads?). We can get text, HTML, XML, or JSON data using AJAX. jQuery has good support for AJAX and because of that, people tend to make AJAX requests with it or a similar library. But remember that jQuery is just JS code that somebody else has already written so lets see how to write this on our own first and then compare to jQuery. One last thing. Before using AJAX, we must be running a server so we need an eclipse project running. You can follow along here


AJAX

Without AJAX, you transmit information to the user by using path variables and request parameters, querying your server from the backend, and reloading the page (or loading a new one) that will contain the data requested. These are synchronous requests (they happen one after the other in the order they're written). Asynchronous means that you can update data on your page while your user continues to use your application. This is because the requests are sent in the order they're written, but the data will be updated in the order that the responses from the server come back. These requests happen in the background and don't require a page reload to populate new elements or data. So as your information updates, your user will dynamically receive new content. These events can be triggered by any event JS has access to. So clicks, mouse movement, key presses, etc. All of these things can trigger an AJAX request and update your page when new content becomes available.

AJAX lets your applications be driven by the data your user is interacting with as opposed to driven by when the user hits a specific page in your application.


AJAX in Action

Some examples of AJAX you are probably familiar with are:

Suggested searches in search engines

Your search engine autocompletes and gives suggestions of what you might be searching for as you type. This is triggered by key events. Every time you type a new character, new suggestions populate because the application is making a request for new data.

Chat Applications

Think Facebook messenger. These applications aren't requiring page reloads every time you send or receive a new message. This is due to AJAX.

Twitter Feeds

Twitter feeds will update dynamically as new tweets come into a page. Again, AJAX calls to see if the database has updated and populating new content.


Local Example

Let's step through a basic AJAX request:

// Creates a new AJAX request
var xhttp = new XMLHttpRequest()
// Sets behavior for when the AJAX request is complete
xhttp.onreadystatechange = function() {
  // Checks the ready state and http status code
  if (this.readyState == 4 && this.status == 200) {
    // Typical action to be performed when the document is ready:
    document.getElementById("asideContent").innerHTML = xhttp.responseText
  }
}
/*
 ** Opens the request and sets the type of request,
 ** location of the data,
 ** and whether the request is asynchronous
 */

xhttp.open("GET", "../sidebar.html", true)
// Sends the request to the server
xhttp.send()

Remote Example

The power of AJAX really lies in its ability to interact with APIs. Let's see an example of that:

var xhr = new XMLHttpRequest()
xhr.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    // Get JSON from the returned string
    const res = JSON.parse(xhr.responseText)
    // Typical action to be performed when the document is ready:
    document.getElementById("asideContent").innerHTML = `<h2>${res}</h2>`
  }
}
/*
 ** Notice in this example we are hitting and actual url
 ** and returning whatever we get from the API we're accessing
 */
xhr.open("GET", "https://swapi.co/api/people/1/", true)
xhr.send()

The response from APIs will almost always be a string. Most times the string represents JSON and it must be parsed.


Conclusion

AJAX becomes a lot more powerful when you can pull data from other APIs such as Twitter, Facebook, Google Maps, Flickr, and countless others. Remember that AJAX always needs a server running to function. if there is no server, you can't make HTTP requests.