Only this week sale up to 80 % on e-learning courses of Java
Get up to 40 % extra points for free! More info
discount week 40

Lesson 20 - AJAX in JavaScript - Basic queries New

Today we are going to learn the popular AJAX technology!

Motivation

We can already change the content of the website using JavaScript and store the data in the repository. But we are still missing something. It's to get data from the internet.

So far, we had to make do with the data that the user entered into the input boxes and that we received with the website, i.e. DOM and images. However, we more often expect a different approach from a web application - the data is often not located on our computer, but we obtain it from servers, i.e. computers somewhere on the Internet. The data is then accessible wherever we log in to the application, which is not the case with localStorage The AJAX technology, which we will get acquainted with today, is used for communication with servers.

AJAX

AJAX (Asynchronous JavaScript And XML) is a designation of a technology with which we can make HTTP requests from JavaScript. It's like entering a web address in the address bar of a browser. The browser sends an HTTP request and downloads the data at the given address (e.g. HTML code of the web page). AJAX allows us to do this directly in Javascript code and especially in the background, without the page on which we are located having to load.

XML in short AJAX can be misleading, because AJAX can download and send any type of data, not just XML. So, for example, the already known JSON, text, HTML, images, videos, and more...

It is important that AJAX does not crash the user interface of our site until the server responds to the request as if the confirm() dialog did, waiting for the user's response. The request is asynchronous. So we can download larger pieces of data in the background and the user can still use the page.

Practical use

So when is AJAX commonly used? We have 2 practical uses here:

  • Creating a SPA (Single Page Aplication) - A common website that we are used to, consists of several HTML pages to which links lead. When you click on the link, the browser deletes everything we see on the page and loads a new page. However, there are no such links in the single-page application. Instead, AJAX starts, which downloads new pages and background data. Then JavaScript inserts new content into the part of the page that we want to change. So we are still on the same page. This can be more comfortable than refreshing an entire window and is more like the user interface of desktop applications. An example of a SPA is Gmail. Note that no matter what you click on, the page will never refresh completely, even if its address changes.
  • Creating add-ons to a page - It's not hard to come up with an example of a page that works with someone else's or our server - such as weather, chat, post ratings, dynamic comment retrieval when scrolling ... AJAX is also very useful for web games where we want to store something, for example, score records for ranking.

In the diagram below, we see the main difference between a classic website and an AJAX-based website:

Classic web

As we can see, on a classic website, the browser simply downloads entire pages from the server and then displays them to the user as the links pass between them. The whole page is always displayed completely again.

SPA

On the web with AJAX, on the other hand, the browser downloads the page and it can then download additional data or send it somewhere without going to another page.

Combination - Web with AJAX

These 2 methods are often combined in practice. E.g. ITnetwork has a separate website for each article, but for example, rating articles with stars sends data to the server using an AJAX request. Nowadays, the user would not even assume that the evaluation of the article should redirect him somewhere. But in the same way, ITnetwork could act as a SPA and look like one page.

In practice, websites with a lot of articles are usually made as separate pages, but smaller information pages (eg websites of a company) or websites that do not explicitly display text (eg Spotify, Netflix, ...) such as SPA. We need AJAX for both solutions.

We usually do not use pure JavaScript to create SPA, but still some frameworks like Angular or React. There is more Javascript code in similar applications and these frameworks will make it easier for us to structure it better. But we still have plenty of time for that:)

API

What exactly is an API? The abbreviation stands for Application Programming Interface. Of course, we all know the graphical user interface (GUI), such as buttons and text boxes. They define how a person communicates with the program. The API defines how another program communicates with a program. However, this interface no longer consists of buttons, but, for example, of sets of functions, their URL addresses, and data structures that we send and receive.

We will work with the web API, so we will mainly deal with URLs to which to send AJAX requests. There's no need to worry - you can get on a server with PHP to create a file time.php code echo time(); and you have an API to gain time. :) But we will not program our APIs, instead, we will use ready-made ones - we will get data about Pokémon. :)

Pokemon API

We will download the data from the pokeapi.co server. At this link, we can test the API directly by entering different URLs in the text box and listing the results.

The API itself is located at https://pokeapi.co/api/v2/. This is our starting URL, which will be the same in every AJAX request. By adding additional parameters to the end of this URL, we will specify what the API should return to us.

Without API parameters, it returns a list of objects that can return:

https://pokea­pi.co/api/v2/
https://pokea­pi.co/api/v2/

It's not just Pokémon, but also abilities or berries. Of course, we will be interested in the pokemon parameter, which will give us a list of pokemon. You can try entering the address https://pokeapi.co/api/v2/pokemon/ in your browser:

https://pokea­pi.co/api/v2/po­kemon/
https://pokea­pi.co/api/v2/po­kemon/

We see that the API server responded with a list of Pokémon. If you notice that there are only the first 20, you are the masters of Pokémon. And if the result is in JSON format, you are the masters of JavaScript. :)

Implementation of AJAX in JavaScript

JavaScript basically offers us 2 implementations of AJAX. The first and older way is to use the XMLHttpRequest class. The second way, calling fetch(), is more modern and straightforward, but uses advanced JavaScript constructs and is much harder to understand. Therefore, fetch() will be discussed at the end of our OOP course and now we will introduce the XMLHttpRequest object.

XMLHttpRequest, I choose you!

An object created from this class is the bearer of our HTTP request, which we use to communicate with the server. We will show you how to use this object to download information about Pokémon.

Creating a request

First we create an instance of the XMLHttpRequest class, the constructor does not take any parameters:

let xhr = new XMLHttpRequest();
Callback

That was easy. Now we need to set up a callback because the request is asynchronous, which means that the execution of JS code does not wait for the result and immediately continues with the next command. This is a big advantage because the window does not jam. Like a document object, the XMLHttpRequest an onload event. It is called automatically when we receive the data and we can use it. We assign callback to the onload as an anonymous function:

xhr.onload = () => {
    document.write(xhr.response);
}

For now, we will just write the data to the page, so that we know what came to us and how to deal with it.

Previously, the onreadystatechange event was used, where it still had to be determined whether the request was in a completed state. Fortunately, this is a thing of the past, but it can be found in older source code.

Sending a request to the API server

However, the request has not yet been sent. So far, we have only defined what will happen to the result. Before sending the request, we must first "open" it:

let apiUrl = "https://pokeapi.co/api/v2/"; // This is the URL that we will be working with.
xhr.open("GET", apiUrl + "pokemon"); // We add the string "pokemon" to the URL - with this, we will get the names of the Pokémons that are available in the database.
xhr.send();

When opening the request, we set the basic parameters:

  • The first, "GET", is the type (HTTP method) of the request. If we only read the data but do not send any, we use the GET method. If we wanted to send data to a server to store it, we would use the POST method, which we will show later in the course.
  • The second parameter is finally the address of the source we are requesting. As we can see, it is probably not a file. URLs are usually routed on servers and data is created dynamically for us. Therefore, we use the term source instead of a file. If we only want to find out what the given resource contains, we do not need to program AJAX, but just enter the URL into the browser, as we have already tried.
After running the code, we get the following result:
Your page
localhost

 

Previous article
Advanced Array Methods In JavaScript
All articles in this section
Object-Oriented Programming in JavaScript
Article has been written for you by Vlasta Řenčová
Avatar
Do you like this article?
No one has rated this quite yet, be the first one!
Passionate reader, student, coder and writer.
Activities

 

 

Comments

To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

No one has commented yet - be the first!