Tutorials
17 May 2020

Learn AJAX: Part 1

By Benji

I’m going to let you in on a secret superpower I have. With a single line of code I can download any website in the world. OK, so maybe it’s not very super. It’s called an HTTP request and your browser does this all the time. But what if you could do it yourself? We call that AJAX.

Disclaimer! This article is for beginners, but it does assume a basic knowledge of HTTP’s structure. If you know the meaning of GET and POST, read on! Otherwise, I highly recommend going straight to the Wikipedia source and boning up.

AJAX is Asynchronous JavaScript and XML. It was developed to request and return XML strings from a server. It’s now widely adopted as a solution for HTTP requesting in the same way your browser does. It helps modern devs to send and get new data asynchronously without changing 20-year-old browser standards.

For example, let’s say we want to send data from a form. A form that looks like this:

With HTML’s <form> element, I can tell the browser to send information via POST or GET request types through a very predictable and typical process:

  1. Gather the form fields.
  2. Do the HTTP request as an action.
  3. Reload the page.

But what if I don’t want to reload? Reloading on form submission is a terrible UX. Don’t get me wrong, we’ll keep the form in working order, exactly the way it is, but modern web design on modern browsers never wants the reload on form submission. Instead, we want AJAX.

[This next bit is going to use jQuery, and I’ll explain why in a moment. Credit: scotch.io]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
$('#form').submit(function(event){
  // stop the form from submitting and refreshing by preventing the default browser behavior
  event.preventDefault();
  
  // gather and validate data fields from the form, typically storing the result as JSON
  var formData = formJSON;

  // AJAX, the jQuery way
  $.ajax({
      type        : 'POST',         // define the type of HTTP verb we want to use (POST for our form)
      url         : 'process.php',  // the url where we want to POST
      data        : formData,       // our data object
      dataType    : 'json',         // what type of data do we expect back from the server
      encode      : true
  })
    // using something called a Promise, we can wait for the servers to respond, then use the results when they come
    .done(function(data) {

        // log data to the console so we can see the result and confirm that it happened
        console.log(data); 
    });
});

To be fair, there are a million ways to use a form. For example, maybe you should house your JS in a function, and call it with onsubmit.

<form onsubmit='validateAndAjax(event)'>
  <input id='email' type='email' placeholder='Email!'>
  <input id='submit' type='submit' value='Submit!'>
</form>
function validateAndAjax(e) {
    // stop the event
    e.preventDefault();

    // my email input validator, free for your use
    if (!/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test($('#email').val())) {
        alert('fail!');
        return false;
    }


    // that AJAX, one more time for the people in the back
    $.ajax({
        // settings for exactly the right HTTP request you want to make
    })
        .success(
            // success things, manipulating the data, callbacks
        )
        .error(
            // HTTP errors, caught here
        );
}

jQuery also makes helper functions that help developers do things faster. They’re for when you are competent. Don’t use them right now. They are not really relevant for this tutorial, but lists are helpful!

  1. $.get() does only HTTP GET requests.
  2. $.getJSON() is $.get()… but only for JSON.
  3. $.getScript() is $.get()… but only for JS (it immediately executes it on arrival).
  4. $.post() does only HTTP POST requests.
  5. $.load() is basically good for plooping out data as if it were paintballs in an AJAX paintball gun.

Cool, so now why did we use jQuery?

Yeah, so jQuery’s AJAX feels pretty simple. It’s just the HTTP method, the url we’re grabbing from, and a body of any data. Maybe you can encode it, or use HTTP headers if you’re getting really fancy.

The original method is a bit more cumbersome. The universally supported base method for AJAX is called XMLHttpRequest(). It is so very much harder for AJAX newcomers to grasp, so I’m going to break it down for you in Part 2!


About the Author:

Benji is a professional web dude. He works at Top Hat making cool web things for money (and sometimes beer).

Disclaimer! Photos on this blog are sometimes taken by me, but sometimes free for use with attribution from Unsplash.com.