SHARE:
Uncategorized

Learning About AJAX

Flatiron School / 22 July 2013

The following is a guest post by Adam Waxman and originally appeared on his blog. Adam is currently a student at The Flatiron School. You can follow him on Twitter here.

As someone who loves UX and design, it is not surprising that I’ve been wanting to learn about JavaScript – the language of the browser that allows for cool client side interactions. I’ve used many JS libraries, but wanted to dive deeper into AJAX. Before today I didn’t even know what it meant, just that it was something I wanted to know more about.

So What is AJAX?

AJAX, or Asynchronous Javascript And XML, is a client side technique for communication with a web server. In other words, it allows you to fetch data ‘in the background’ without having to reload a whole page.

In a typical web request, you send a URL request to the server and the server responds with the corresponding HTML, CSS, and JavaScript that generates a full new page in your browser.

In contrast, in a typical AJAX request, the HTML, CSS, and JavaScript is already loaded. Instead of making a URL request for another whole page, you use JavaScript to talk to the server and receive smaller pieces of information that can range from HTML to other data formats like JSON and XML. The JavaScript then acts on the response and updates the page accordingly, without having to refresh the entire page.

What does an AJAX request look like?

At a high level an AJAX request consists of the URL you a making a request to, and then corresponding settings to handle the response. Below are a few of the more popular callbacks that make up the settings:

  • success: what to do if the URL request is successful
  • error: what to do if the URL request is unsuccessful
  • timeout: how long to allow the URL request to run before an error message pops up
  • beforeSend: runs before the AJAX request, good place to put a spinner
  • complete: runs after both success and error, good place to stop a spinner

Examples

Example 1: makes a request to ‘index.html’ and then inserts the response into the item in the DOM that has a class called “hello-world”

These three examples all make a request to the url ‘profile.html?userId=1’ and show the various ways to send parameters with a request. In example 2 the data is put manually into the URL. In example 3 the data is put into a JavaScript object. Lastly, in example 4 the AJAX request pulls data from HTML, which when combined with ERB tags can make the request very dynamic.

Example 5 demonstrates some of the callback settings. In this AJAX request, if the response is not successfully made it will stop the request after 3 seconds (3000 milliseconds). It also demonstrates common code for adding a loading animation while the request is being made.

Dealing With the Blank Screen problem…start With a Blank Sheet of Paper Instead. Previous Post Starting My Own App Next Post