Making AJAX calls in pure JavaScript

Making AJAX calls in pure JavaScript

TL;DR

In this, beginner oriented, post I’ll show you how to make AJAX calls in pure JavaScript, step by step with few examples.

So, what is AJAX?

AJAX stands for:

  • Asynchronous – means that if you start some request (call some API), you can move on to another task before that request is finished. This is the direct opposite of when you execute something synchronously – in that case, you have to wait for it to finish before moving on to another task.
  • JavaScript – the best language ever ?
  • And – added ‘And’ as three letter acronyms just don’t cut it anymore
  • XML – Extensible Markup Language that no one on the web uses anymore :), JSON FTW 🙂

OK, but what does it do?

AJAX lets you load some new data to your web page, without the need to reload the whole webpage. This behavior makes your site feel faster and more responsive. Not to mention that nowadays this is the defacto standard. Namely, if you come across a site on which you fill out a form and submit it, and then it has to reload, the site basically screams at you: “OOOOOLD!”.

Where can I see it in action?

I’d argue that you can see it in action on any decent webpage nowadays. For example, load the Google website in your browser, and open the dev tools. On Chrome, you can do that with right-clicking a mouse and selecting Inspect, and then clicking in the Network tab.

If you also select the XHR filter and start writing something in the search bar, you’ll start seeing the AJAX requests. Very important to note here is that the site didn’t reload.

If you click on one of these items in the Name column and then click the Response tab, you’ll see the actual response that the server sent back.

⚠️ This is an important concept to remember: web works in a Request/Response kind of a way. A client (your browser) sends Request to some server, and the server returns a Response, which then client processes.

Another example of AJAX in action is when you are presented with a newsletter signup form on some site. You fill out the name and an email address, click send, and the site doesn’t refresh. Instead, you get the message right there like “you’ve been subscribed, check your email”.

This is great, but how do I use it?

No one likes the theory, but it actually may help here. To use AJAX in JavaScript, you need to do four things:

  • create a XMLHttpRequest object
  • write the callback function
  • open the request
  • send the request

I know I know, you must be like:

OK, OK, so let’s take those steps from above and turn them into code:

  • create a XMLHttpRequest object
    • var xhr = new XMLHttpRequest();
    • of course, you can name the variable differently as well, but I hope you know this much about JS, or programming in general, so won’t go into that here ?)
  • write the callback function
    • xhr.onreadystatechange = function() {};
  • open the request
    • xhr.open('GET', 'http://www.google.com');
    • the first parameter is the type of the request. Another common one is ‘POST’, and we’ll talk about it more in the next post.
    • the second parameter is the URL (a link) to which you want to send the request. In our case, that’s Google’s website.
  • send the request
    • xhr.send()
    • finally, send the request

If we put it all in one place, we get this:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {};
xhr.open('GET', 'http://www.google.com');
xhr.send()

Fine, but, erm, where do I test this?!

You’ll be a bit disappointed to learn that the code above doesn’t do much.

Besides, where could you test this? Well, for one thing, you can’t test it on your local machine in a way of creating an index.html and opening it in your browser.

You have to test this on some website that’s online. Examples speak more than words, so let’s go and open up http://www.google.com in your browser.

Now let’s do a few things:

  • open the dev tools
  • select the Elements tab
  • right click the html element and select Edit as HTML
  • delete everything and click outside of the box that appears and you’ll end up with a blank page
  • add a div to the body tag like this: <div id="result">Testing</div>

Next, in the Console tab of the dev tools, write this:

var clearResult = function() {
    document.getElementById('result').innerHTML = '';
}

and then call it like this: clearResult().

The purists will kill me for using var instead of let ?

To save you a lot of trouble by figuring out why using clear as the function name won’t work, check out this post.

Now, copy paste the following code to the Console tab and press Enter to execute it:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState === 4){
        document.getElementById('result').innerHTML = xhr.responseText;
    }
};
xhr.open('GET', 'https://www.google.com');
xhr.send();

Woilà, what do you get? You just loaded Google’s main page back in ?

AJAX can only go so far, most of the time

If you try playing out with the URL in the open command, you’ll soon stumble upon CORS. It basically means that, if your domain is google.com, then you can’t load the data from:

  • some other domain like example.com
  • a subdomain like abc.google.com
  • a different port on the same domain like google.com:8080
  • a different protocol like http

There are ways to get around this (server proxy on the same domain, JSONP, CORS setting on the domain server, using browser plugins), and I encourage you to dig deeper and learn more about it on your own (or wait until I write about it in some other post).

I want more examples

Great, happy to provide you with them.

Load up my test site. Copy the AJAX function from above and replace https://www.google.com with http://nikola-breznjak.com/_testings/ajax/test1.php and observe what happens.

Try changing the link to http://nikola-breznjak.com/_testings/ajax/test1.php?ime=Nikola and see what happens then. This is called sending the parameter (ime) in the URL. Which brings me to the following difference…

GET vs. POST

There are two common methods for sending HTTP requests:

  • GET – used for most requests. The browser uses a GET method whenever it requests a new web page, CSS file, image, and so on. Use GET when you want to “get” something from the server.
  • POST – frequently used with web forms to send data to the server. Use POST when sending data that will be stored, deleted or updated on the server.

You can send parameters with GET in the URL, and that’s a benefit as well as the downside, as there’s a limit to the length of the parameters in a GET request (2048 chars), as well as there’s a security issue. With POST you can send way more data, and in a secure way.

XML vs. JSON

XML is short for eXtensible Markup Language, and you can learn more about it here. It used to be for transmitting structured data that’s easily parsable by computers. You’ll notice it’s similar to HTML; for example:

<phones>
    <phone>+38598123456</phone>
    <phone>+38598654321</phone>
</phones>

Though, TBH, it’s not used on the web, so I won’t bore you with it. What is used, extensively, on the web these days is JSON. It looks very much like JavaScript object literal, with one addition – the key also needs to be enclosed with double quotes. For example:

[
    {"phone":"+38598123456"},
    {"phone":"+38598654321"}
]

This is an array of objects which consist (currently) of one property called phone.

Mini Project

So, mini project time now. Let’s suppose that you work at a job where your boss says that you need to update this page to have the sidebar load the advertisement from the API that can be found here.

He also adds that you need to make it consistent to the current design (Bulma rocks btw!) and make the price be of different colors based on the following rules:

If the price (cijena in the API response) is below 100 make it some greenish color. If it’s between 100 and 300, make it some blueish color. If it’s more than 300, make it red.

How are you going to do it?

I encourage you to try it out for yourself and only then come back and see my approach below.

You should have this in the end:

You can totally test this now by pasting the code below in the Console on this page.

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
    if (xhr.readyState === 4){
        var oglasi = JSON.parse(xhr.responseText);
        var oglasiHTML = '';
        for (var i=0; i<oglasi.length; i++){
        var klasaCijene = '';
        if (oglasi[i].cijena <100){
            klasaCijene = 'is-success';
        }
        else if (oglasi[i].cijena > 100 && oglasi[i].cijena < 300){
            klasaCijene = 'is-info';
        }
        else if (oglasi[i].cijena > 300){
            klasaCijene = 'is-danger';
        }

            oglasiHTML += '<p><span class="tag ' + klasaCijene + '">' + oglasi[i].cijena + '</span>' + ' ' + oglasi[i].tekst + '</p>';
        }

        document.getElementById('oglasi').innerHTML = oglasiHTML;
    }
};

xhr.open('GET', 'http://nikola-breznjak.com/_testings/ajax/test2.php');
xhr.send();

Conclusion

That’s all folks, hope it was useful and see you next time when I’ll show you how much easier it is to do all of this with a jQuery. Sure sure, in some later posts we’ll come to the fetch API as well. But first, baby steps ?

Written by Nikola Brežnjak