Javascript AJAX – A 5 Minutes Beginner’s Tutorial

INTRODUCTION

THE STONE AGE IS OVER

Welcome to a beginner’s tutorial on AJAX in Javascript. Yes, the Stone Age of the Internet is long over. If you are still doing “static HTML” or “post-and-reload the entire page” – It is time to explore the power of AJAX to spice up your website. This guide will walk you through the basics of AJAX in Javascript, and a couple of examples of how it is typically used. Read on to find out!

ⓘ I have included a zip file with all the example code at the end of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

 

PREAMBLE

DOWNLOAD & NOTES

First, here is the download link to the example source code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICK NOTES

There is nothing to install, so just download and unzip into a folder. If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

SECTION A

AJAX BASICS

Before we dive into the examples, let us start with a small section to explain what AJAX is. Feel free to skip this part if you already know all of these.

 

WHAT IS AJAX!?

AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating better, faster, and more interactive web applications.

TutorialsPoint

In short, AJAX is not referring to the cleaning agent. 😆 But in layman terms:

  • Load content without refreshing the entire page.
  • Submit a form without redirecting to another page.
  • Basically, send/retrieve data from the server without reloading nor “freezing” the entire page.

 

 

WHY AJAX – THE OLD DAYS

Once upon a time in the Stone Age of the Internet, how things work are painfully slow and clunky. For example, in an eCommerce site:

  • To add an item to the cart – We have to submit an HTML form, wait for the server to process, then reload the entire products page.
  • To show the shopping cart – We will have to navigate away from the products page, load an entirely separate “shopping cart” page.
  • The same for removing and changing the quantity of an item in the cart – We have to submit a form, wait for server to process, reload the entire shopping cart page.

 

WHY AJAX – SPEEDING THINGS UP

Smart monkeys eventually realize that it is a pain to reload pages unnecessarily, and came up with AJAX:

  • The “add to cart” request can run in the background, no need to reload the entire page.
  • The same for change quantity, remove items.
  • To show the shopping cart, we can dynamically load “just the cart contents”, and update the HTML accordingly.
  • The best part of AJAX is being asynchronous. Meaning, we can run several AJAX requests in parallel, and it will not “freeze” the page. The user can still use the page while an “add to cart” is processing in the background.

 

SECTION B

HOW TO AJAX

Now that you have an idea of what AJAX is and what it can do, let us go into how to actually use it.

 

MINIMAL AJAX

1a-minimal.js
var xhr = new XMLHttpRequest();
xhr.open("GET", "0-dummy.php");
xhr.send();

To do an AJAX request, all we need is to:

  • Create a new var xhr = XMLHttpRequest() object.
  • Set the method to use and target script xhr.open('POST OR GET', "SCRIPT.PHP").
  • Finally, send out the AJAX request with xhr.send().

That’s all to the “complicated” AJAX. But please take note of a couple of things:

  • AJAX will not work with file://, open the test script with a proper http:// instead.
  • We can pretty much request any type of file on the server – HTML, text, image, server-side script, etc…
  • Use absolute URL if you are having trouble with the path – xhr.open("GET", "http://MY-SITE.com/PATH/SCRIPT")

 

 

AJAX EVENTS

1b-events.js
// (A) INIT
var xhr = new XMLHttpRequest();
xhr.open("GET", "0-dummy.php");

// (B) WHEN AJAX IS RUNNING
xhr.onprogress = function(evt){
  console.log(evt);
};

// (C) WHEN SERVER RESPONDS
xhr.onload = function(evt){
  console.log(evt);
  console.log(this.status); // HTTP response code
  console.log(this.response); // Response from server
};

// (D) WHEN ERROR OCCURS
xhr.onerror = function(evt){
  console.log(evt);
};

// (E) GO!
xhr.send();

Of course, it will be dumb if we just send out an AJAX request and not do anything with it. So here are 3 AJAX events that you should know:

  • onprogress: When the AJAX request is fired (but not yet complete).
  • onload: Triggered when the AJAX request is complete.
  • onerror: Triggered when an error occurs, for example, no response from the server.

This should be straightforward, but a couple of things to take note:

  • onload will fire as long as the server responds, even when an error occurred on the server-side.
  • For example, when a file is not found, the server will respond with “404 file not found”. When permission is required to access your specified script, the server responds with a “403 unauthorized”.
  • On this note, we can get the HTTP response code in onload via this.status, and the actual text response via this.response – I will leave a link to a reference of HTTP response codes in the extras section below.
  • It will be good to check and deal with this response code, and not assume that the server will always respond with 200 (OK) – if (this.status!=200) { SERVER ERROR }.

 

POST DATA WITH AJAX

1c-post.js
// (A) APPEND FORM DATA
var data = new FormData();
data.append('Name', 'John Doe');
data.append('Email', 'john@doe.com');
// Add more as required - data.append('KEY', 'VALUE');

// (B) INIT AJAX
var xhr = new XMLHttpRequest();
xhr.open("POST", "0-dummy.php");

// (C) WHEN THE PROCESS IS COMPLETE
xhr.onload = function(evt){
  if (this.status==200) {
    console.log(this.response);
  } else {
    console.log("SERVER ERROR");
    console.log(this.status);
    console.log(this.response);
  }
};

// (D) SEND
xhr.send(data);

Yep, we can also append data to AJAX requests and POST it to the server, just like submitting forms using a good old HTML – But we don’t have to redirect or reload the entire page… Nor is having an actual <form> necessary.

 

 

APPENDING QUERY STRING (GET)

1d-get.js
// (A) BUILD URL QUERY STRING
var data = new URLSearchParams();
data.append('Name', 'John Doe');
data.append('Email', 'john@doe.com');
// Add more as required - data.append('KEY', 'VALUE');
var url = "0-dummy.php?" + data.toString() ;
 
// (B) INIT AJAX
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
 
// (C) WHEN THE PROCESS IS COMPLETE
xhr.onload = function(evt){
  if (this.status==200) {
    console.log(this.response);
  } else {
    console.log("SERVER ERROR");
    console.log(this.status);
    console.log(this.response);
  }
};
 
// (D) SEND
xhr.send();

Don’t like using POST? Here is how we form a query string and append it to the URL instead.

 

SET THE TIMEOUT

1e-timeout.js
var xhr = new XMLHttpRequest();
xhr.timeout = 5000; // TIMEOUT IN MILISECONDS
xhr.open("GET", "0-dummy.php");
xhr.send();

Don’t want to wait too long for the server response? Or want to give the server more time for processing? We can easily do it by tweaking the timeout property.

 

CANCELING AJAX REQUESTS

1f-cancel.js
// (A) INIT & SEND
var xhr = new XMLHttpRequest();
xhr.open("POST", "0-dummy.php");
xhr.send();

// (B) ABORT MISSION
xhr.abort();

Finally for those of you who are curious – Yes, we can cancel AJAX requests. We won’t be doing this normally, but you can easily abort it using the abort() function.

 

 

SECTION C

COMMON USAGE EXAMPLES

So far so good? That should pretty much cover all the AJAX basics, but here are a few typical ways in which we can use AJAX.

 

EXAMPLE 1) DYNAMICALLY LOAD CONTENTS

2a-contents.html
<script>
function fetch(){
  var xhr = new XMLHttpRequest();
  xhr.open("GET", "README.txt"); // Will work with HTML, PHP, ASP, etc...
  xhr.onload = function () {
    if (this.status==200) {
      document.getElementById("container").innerHTML = this.response;
    } else {
      alert("ERROR LOADING FILE!");
      console.log(this.status);
      console.log(this.response);
    }
  };
  xhr.send();
}
</script>
<input type="button" value="Click to AJAX load" onclick="fetch();"/>
<div id="container"></div>

But of course, you can use it to do something more useful, like showing the contents of the shopping cart, or display products within a selected category.

 

EXAMPLE 2) FETCH INFORMATION/DATA FROM SERVER

2b-fetch.html
<script>
function fetch() {
  var xhr = new XMLHttpRequest();
  xhr.open('POST', "2c-dummy.txt");
  xhr.onload = function () {
    if (this.status==200) {
      var fruits = JSON.parse(this.response),
          container = document.getElementById("container"),
          list = document.createElement("ul"),
          item = null;
      fruits.forEach(function(fruit) {
        item = document.createElement("li");
        item.innerHTML = fruit;
        list.appendChild(item);
      });
      container.innerHTML = "";
      container.appendChild(list);
    } else {
      alert("ERROR LOADING FILE!");
      console.log(this.status);
      console.log(this.response);
    }
  };
  xhr.send();
}
</script>

<input type="button" value="Click to AJAX load" onclick="fetch();"/>
<div id="container"></div>
2c-dummy.txt
["apple","orange","pear","banana","watermelon","papaya"]

Apart from HTML, you can also use AJAX to fetch raw JSON and XML data from the server. Again, you can use it to do stuff that is more productive, such as getting the total number of items in the cart, and/or the total amount.

 

 

EXAMPLE 3) SUBMIT/POST FORMS

2d-form.html
<script>
function process() {
  // (A) GET FORM DATA
  var data = new FormData();
  data.append('email', document.getElementById("form_email").value);
  data.append('password', document.getElementById("form_password").value);

  // (B) AJAX SEND
  var xhr = new XMLHttpRequest();
  xhr.open("POST", "0-dummy.php");
  xhr.onload = function () {
    if (this.status==200) {
      console.log(this.response);
    } else {
      alert("ERROR LOADING FILE!");
      console.log(this.status);
      console.log(this.response);
    }
  };
  xhr.send(data);
  return false;
}
</script>

<form onsubmit="return process()">
  Email: <input type="email" id="form_email" required autofocus/><br>
  Password: <input type="text" id="form_password" required/><br>
  <input type="submit" value="Submit"/>
</form>

Can we submit a form without reloading the page? Yes, let us say that we have a simple user login form, and here is how to submit it with AJAX.

 

EXTRAS

USEFUL BITS & LINKS

We have come to the end of the examples, and here some extras and links that you may find useful.

 

SUMMARY

Functions
FunctionDescription & Parameters
open (method, url, async, user, password)Primes the AJAX request.

  • method – POST or GET.
  • url – Target URL to send the AJAX request to.
  • async – True or false, optional and defaults to true.
  • user – Optional, only for accessing pages that are protected.
  • password – Optional, only for accessing pages that are protected.
send (data)Sends AJAX request to the server.

  • data – Data to append to the AJAX request, optional.
abort ()Aborts the AJAX request – No parameters.
Properties
PropertyDescription
responseContains the response from the server.
timeoutTimeout in milliseconds.
statusHTTP status code.
Events
EventDescription
onloadFired when the AJAX request is complete.
onprogressFired as the AJAX request is running.
onerrorFired when the AJAX request encounters an error.

 

SUPPORTING LEGACY BROWSERS

Before we end this tutorial, I hate to break some bad news. If you have to support the ancient browsers, the onload event is not available and all the above examples will work properly. So to support legacy browsers, here is the “old school way” of doing it, by reading the onreadystatechange and HTTP status code.

2e-back-compat.js
function fetch(){
  var xhr = new XMLHttpRequest();
  xhr.open("GET", "0-dummy.php");
  xhr.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("container").innerHTML = this.responseText;
    }
  };
  xhr.send();
}

As for the readyState property, here are the status codes:

CodeDescription
0The object is created.
1The open function has been set.
2A request has been sent, but the process is not yet complete.
3Download in progress.
4The AJAX operation is complete.

 

A SMALL WARNING FOR SEO BUFFS

AJAX is useful, but don’t be overzealous in implementing it everywhere. Modern search engines are smart enough to wait for some AJAX parts to finish loading. But they don’t necessarily wait for everything and evaluate the entire page. So if your “main contents” are loaded via AJAX, you might want to reconsider – As search engines may leave it out for evaluation, and this will hurt your chances of ranking instead.

 

LINKS & REFERENCES

 

CHEATSHEET

Vanilla AJAX (Click to Enlarge)

 

CLOSING

WHAT’S NEXT?

Thank you for reading, and we have come to the end of this guide. I hope it has helped you to better understand AJAX. If you have anything to add to this guide, please feel free to comment below. Good luck and happy coding!

6 thoughts on “Javascript AJAX – A 5 Minutes Beginner’s Tutorial”

  1. Hi there, I’m late to the game but need a bit of clarification on form submission and retrieval data. Is there a–or that should be; what is the vanilla JanaScript equivalent of the jQuery html(result).show()?
    I’m trying to follow some of the example code here (specifically 3a-ajax-fetch.html) with no luck as my results are HTML and not JSON encoded.
    Any suggestions?
    Thanks for the tutorial and for any help.

    1. I don’t catch your question, but you are confusing yourself. What you are trying to do is exactly explained in 2a-ajax-contents.html. $('#ELEMENT').html(RESULT).show() does 3 different things:

      • $('#ELEMENT') does document.getElementById('ELEMENT')
      • .html(RESULT) does .innerHTML = RESULT
      • .show() simply sets the .style.visibility = "visible"
  2. Thank you for these examples on your website. For example: the dime FINALLY dropped in understanding what AJAX does & why it’s handy to use. Being around people on my projects for years and years using AJAX, that’s something great.
    I really like your small steps approach and your commented code from the ZIPs.
    You, sir Toh – !evil Sith Lord, are a great teacher.
    Thanks again, Bob

  3. Can you elaborate on #3? If I have $name = $_POST[‘name’]; function valid_name(){ if($name = “” ) { return false; } else { return true; }}
    How would that relate to $results? Thanks.

    1. Sorry for the confusion, I have improved on the example a little. The $results variable is used to formulate the server-side response on the status of the processing – If it is successful or if an error has occurred. It will be later picked up on the Javascript side for further processing – var res = JSON.parse(this.response); if (res.status==true) { … }

Leave a Comment

Your email address will not be published. Required fields are marked *