HomeGitHubAboutBlog

Let's fetch AJAX

25 February, 2020 - 3 min read

What is AJAX?

AJAX stands for Asynchronous JavaScript and XML. It is a way for front-end code to communicate with the backend by making asynchronous API calls. It allows you to update small parts of a web page, rather than refreshing the whole page. For example: Posting a tweet on Twitter. The tweet will appear after you press “submit”, but the page itself will not be reloaded.

Common Mistakes / Misconceptions

  • Most web applications that use AJAX don't use XML anymore, despite the name "AJAX"; instead, they transport data using other formats, most commonly as JSON.
  • AJAX is technically not an API and it is not a library in and of itself. It is a set of techniques that uses the XMLHttpRequest (XHR) API. There are many JavaScript libraries, including jQuery, that contain wrappers around the XHR API, and these are colloquially called AJAX libraries.
  • Because AJAX is asynchronous, you must pass in a callback function to handle the received data.

Threads of Execution

A thread of execution in computer science is a way for a program to divide (termed "split") itself into two or more simultaneously running [tasks].

Javascript runs in a single thread, which simply means it runs one command at a time. Events are queued and executed in the order they are written.

Examples of an AJAX call

You can basically use it to get data from different APIs.

$.ajax("some-url", {
  success: data => {
    /* do something with the data */
  },
  error: err => {
    /* do something when an error happens */
  },
})

Make fetch happen

The Fetch API provides an interface for fetching resource. It is similar to the XMLHttpRequest, but the new API provides a more powerful and flexible feature set.

Getting data with Fetch is easier. You just need to provide Fetch with the resource you're trying to fetch.

async function getData() {
  //await the response of the fetch call
  let response = await fetch("https://api.github.com/users")
  //proceed once the first promise is resolved.
  let data = await response.json()
  //proceed only when the second promise is resolved
  return data
}
//call getData function
getData().then(data => console.log(data))
//To do something after the resource is fetched, you write it in a  `.then`  call:

Fetch returns a Promise, which is a way to handle asynchronous operations without the need for a callback.

Support for Fetch is great. All major browsers (with the exception of Opera Mini and old IE) support it natively, which means you can safely use it. If you need support anywhere it isn't natively supported, you can always depend on this handy polyfill.