- Making AJAX calls in pure JavaScript, the old way
- TL;DR
- So, what is AJAX?
- OK, but what does it do?
- Where can I see it in action?
- This is great, but how do I use it?
- Fine, but, erm, where do I test this?!
- AJAX can only go so far, most of the time
- I want more examples
- GET vs. POST
- XML vs. JSON
- Mini Project
- Conclusion
- AJAX Call in JavaScript with Example
- AJAX call via XMLHTTPRequest
- Using JavaScript fetch prototype
- An example use case scenarios of using AJAX in an application
Making AJAX calls in pure JavaScript, the old way
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?
- 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 😉)
- xhr.onreadystatechange = function() <>;
- 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.
- 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.
- 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: Testing
Next, in the Console tab of the dev tools, write this:
var clearResult = function()
and then call it like this: clearResult() .
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:
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:
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; ielse if (oglasi[i].cijena >= 100 && oglasi[i].cijena < 300)< klasaCijene = 'is-info'; >else if (oglasi[i].cijena >= 300) < klasaCijene = 'is-danger'; >oglasiHTML += '
' + oglasi[i].cijena + '' + ' ' + oglasi[i].tekst + '
'; > 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 💪
AJAX Call in JavaScript with Example
This is a pure JavaScript solution to use AJAX without jQuery or any other third-party plugins.
The AJAX is a way of sending requests to the server asynchronously from a client-side script. In general, update the UI with server response without reloading the page.
I present two different methods of calling backend (PHP) with JavaScript AJAX.
This tutorial creates simple examples of both methods. It will be an easy start for beginners of AJAX programming. It simply reads the content of a .txt file that is in the server via JavaScript AJAX.
If you want to search for a code for using jQuery AJAX, then we also have examples in it.
AJAX call via XMLHTTPRequest
This example uses XMLHttpRequest in JavaScript to send an AJAX request to the server.
The below script has the following AJAX lifecycle to get the response from the server.
- It instantiates XMLHttpRequest class.
- It defines a callback function to handle the onreadystatechange event.
- It prepares the AJAX request by setting the request method, server endpoint and more.
- Calls send() with the reference of the XMLHttpRequest instance.
In the onreadystatechange event, it can read the response from the server. This checks the HTTP response code from the server and updates the UI without page refresh.
During the AJAX request processing, it shows a loader icon till the UI gets updated with the AJAX response data.
#loader-icon
How to make an AJAX Call in JavaScript
This example uses plain JavaScript to make an AJAX call.
It uses good old JavaScript's XMLHttpRequest. No dependency or libraries!
Using JavaScript fetch prototype
This example calls JavaScript fetch() method by sending the server endpoint URL as its argument.
This method returns the server response as an object. This response object will contain the status and the response data returned by the server.
As like in the first method, it checks the status code if the “response.status” is 200. If so, it updates UI with the server response without reloading the page.
#loader-icon
How to make an AJAX Call in JavaScript using Fetch
This example uses core JavaScript's Fetch API to make an AJAX call.
JavaScript's Fetch API is a good alternative for XMLHttpRequest. No dependency or libraries! It has wide support with all major browsers.
An example use case scenarios of using AJAX in an application
AJAX is a powerful tool. It has to be used in an effective way wherever needed.
The following are the perfect example scenarios of using AJAX in an application.
- To update the chat window with recent messages.
- To have the recent notification on a social media networking website.
- To update the scoreboard.
- To load recent events on scroll without page reload.