Ajax and Async Code
Tags: javascript, ajax, async, fetch
Published: 2019-08-20 18:16:29

---
title: Ajax and Async Code
published: true
description: A look into what Ajax is and how it relates to JS
tags: JavaScript, Ajax, Async, Fetch
---

# What is Ajax and Why?

So first of all, I would like to say that every time I talk about AJAX I can't help but think of Jax, the fighter in Mortal Kombat with the two metal arms...anyone else?

![](https://vignette.wikia.nocookie.net/mkwikia/images/4/4e/JAX.gif/revision/latest?cb=20090531180518)
<figcaption>Jax Briggs</figcaption>


Ajax is a _technique_ for accessing web servers from a web page. It stands for "Asynchronous JavaScript and XML". Yeah, that's a mouthful, so let's take a second to unpack that.

![](https://media.giphy.com/media/NbgeJftsErO5q/giphy.gif)
<figcaption>When you see those bugs start crashing things...</figcaption>

Now, before you start claiming that Ajax is some sort of API or NPM package, you should understand that Ajax is more so a term that describes a model built up of a multitude of technologies, of which the **XMLHttpRequest** object is the most pivotal.

### [Those sweet MDN docs for a more technical read](https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX) 

An **XMLHttpRequest object**, or XHR for short, allows you to interact with servers! Yes, you too can have the powerrrr!

![](https://media.giphy.com/media/gC42Rz5MaVJGNKIxMC/giphy.gif)
<figcaption>How my lame jokes make all my friends feel</figcaption>

 This is where things get super interesting. I know, as if they weren't interesting before right!? So when looking at MDN, the key thing to realize about what XHR allows us to do as developers is this...

>"You can retrieve data from a URL 
> without having to do a full page refresh." 
- with love, the MDN gods

When this ability is injected into something like say ReactJS, we're able to update specific pieces of our web apps behind the curtain while the user is provided a seamless experience. The term for this action, of showing our users a stable clean site in one hand while completing our magic trick with the other hand is _Asynchronous request_. 

![](https://media.giphy.com/media/AEMyf9Oj6MpS8/giphy.gif)
<figcaption>"Don't look! Coding is much harder that it appears! Shhhh"</figcaption>

At this point, we're left with two lingering questions.

1. What is the _XMLHttpRequest_ object?
2. What does _Asynchronous_ mean?

To create an XHR request, you may have written something like what I have below in the past if you've been in the game longer

<pre>
const request = new XMLHttpRequest();
</pre>

Thanks to the progress (and headaches) of other developers, we now have a multitude of libraries or the more commonly used _Fetch API_ that allows use to both read and write more universally understandable requests.

An example of a fetch request to an api would be as follows

### [More on Fetch at MDN](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)

<pre>

fetch('https://swapi.co/api/people/1')
.then(response => response.json())
.then(data => console.log(data, 'STAR WARSSSSS'))

</pre>
<figcaption>I used this api here, "https://swapi.co/", try it!</figcaption>

Although XML has a large part to play, these requests can pull different data types like JSON above. 

When we console.log(), our object looks as follows

<pre>
{
	"name": "Luke Skywalker",
	"height": "172",
	"mass": "77",
	"hair_color": "blond",
	"skin_color": "fair",
	"eye_color": "blue",
	"birth_year": "19BBY",
	"gender": "male",
	"homeworld": "https://swapi.co/api/planets/1/",
	"films": [
		"https://swapi.co/api/films/2/",
		"https://swapi.co/api/films/6/",
		"https://swapi.co/api/films/3/",
		"https://swapi.co/api/films/1/",
		"https://swapi.co/api/films/7/"
	],
	"species": [
		"https://swapi.co/api/species/1/"
	],
	"vehicles": [
		"https://swapi.co/api/vehicles/14/",
		"https://swapi.co/api/vehicles/30/"
	],
	"starships": [
		"https://swapi.co/api/starships/12/",
		"https://swapi.co/api/starships/22/"
	],
	"created": "2014-12-09T13:50:51.644000Z",
	"edited": "2014-12-20T21:17:56.891000Z",
	
</pre>


Asynchronous basically means that, multiple things can occur at the same time. If you click a button to see more star wars facts, your JavaScript page doesn't have to stop what it's doing, it can keep showing the user a cool interactive site, and in the background start requesting data from an API endpoint. 

Most browsers today run on a JavaScript based engine, and JavaScript itself is used to running synchronously, meaning it must wait for one task to complete before moving on to the other, in the order the tasks were coded to be created.

Usually the JS engine is not the only engine that's running. We have items like the rendering engine, or as we've seen, elements that request data through an HTTP request. So although the JS code is running in a synchronous way, there are other pieces that are doing work asynchronously. 

JS has an execution stack, built of execution contexts that are created and run in the order that they were created. Once complete, each execution context drops off.

Parallel to this is the **Event Queue**, made up of events and notifications of events that are occurring, like button click for example.

BUT, here's a big but, JS only starts attending to the event queue AFTER the execution-stack is emptied. 

If an event causes a function to be created and executed, an execution context is created when we reach that event, like handling an HTTP Request as we've seen above with our fetch. And so, it is placed in the call-stack to be run. And that's it!

JS is continuously running an Event Loop, to keep checking periodically if there is something else to do, this is what allows JavaScript to go back and take a look at events after it's initial execution stack is exhausted. 

Events are looked at Synchronously by JS, but the browser will place them into the event queue in an Async manner. JS can continue to load all the files and functions you've written out in your app, while specific triggers and events can be thrown in independent of the JS Engine, to a certain degree.


![](https://media.giphy.com/media/mp0X9k8eVoVgI/giphy.gif)