AJAX and Axios
Tags: Ajax, Full Stack, Axios, Backend

It is always confusing when I saw these two keywords. What is AJAX and what is Axios. Why we use them and what are the functions of these two. What is the difference?

1.HTTP requests in the browser

There are many ways to make HTTP requests in the browser. For example. URL bar, Links, JavaScript, and submitting forms(GET/POST). All of these make the browser navigate and retrieve new documents.

views are stored on the server and served up as HTML pages

when a user goes to a new page, the browser navigates in totality, refreshing and retrieving a brand new HTML document

each page retrieves stylesheets, scripts, files, etc

2.AJAX

Asynchronous JavaScript And XML. AJAX is not a programming language. AJAX allows web pages to be updated asynchronously by exchanging data with a web server behind the scenes. This means that it is possible to update parts of a web page without reloading the whole page.

Workflow:

(1)An event occurs in a web page(the page is loaded, a button is clicked)

(2)An XMLHttpRequest object is created by JavaScript

(3)The XMLHttpRequest object sends a request to a web server

(4)The server processes the request

(5)The server sends a response back to the web page

(6)The response is read by JavaScript

(7)Proper action (like the page update) is performed by JavaScript

异步的JS和XML技术，指的是一套综合了多项技术的浏览器端网页开发技术， AJAX应用可以仅向服务器发送并取回必须的数据，并在客户端采用JS处理来自服务器的回应， 在服务器和浏览器之间交换的数据大量减少，服务器回应更快，指的并不是单一的技术，而是有机地利用一系列相关的技术。以异步的方式向服务器提交需求。

Ajax is a set of web development techniques using many web technologies on the client side to create asynchronous web applications. With Ajax, web applications can send and retrieve data from a server asynchronously (in the background) without interfering with the display and behaviour of the existing page. By decoupling the data interchange layer from the presentation layer, Ajax allows web pages and, by extension, web applications, to change content dynamically without the need to reload the entire page. In practice, modern implementations commonly utilize JSON instead of XML. Ajax is not a single technology, but rather a group of technologies. HTML and CSS can be used in combination to mark up and style information. The webpage can then be modified by JavaScript to dynamically display — and allow the user to interact with — the new information. The built-in XMLHttpRequest object, or since 2017 the new “fetch()” function within JavaScript, is commonly used to execute Ajax on webpages, allowing websites to load content onto the screen without refreshing the page. Ajax is not a new technology, or different language, just existing technologies used in new ways.

Asynchronous JavaScript And XML

Making background HTTP requests using JavaScript

Handling the response of those HTTP requests with JavaScript

No page refresh necessary

AJAX allows us to build Single Page Applications. (An SPA is a web application or web site that interacts with the user by dynamically rewriting the current page rather than loading entire new pages from a server.) SPAs mean no reload or “refresh” within the user interface.

3.Axios

Axios is a popular, promise-based HTTP client that sports an easy-to-use API and can be used in both the browser and Node.js. Making HTTP requests to fetch or save data is one of the most common tasks a client-side JavaScript application will need to do.

Axios is a promise-based HTTP client for JavaScript. It allows you to:

Make XMLHttpRequests from the browser

Make HTTP requests from node.js

Supports the Promise API

Automatic transforms for JSON data

Axios provides more functions to make other network requests, matching the HTTP verbs that you wish to execute.

3.1 Use Axios

npm install axios

bower install axios

CDN script

3.2 Fetch VS Axios

Fetch API is built into the window object and therefore doesn’t need to be installed as a dependency or imported in client-side code

Axios needs to be installed as a dependency. However, it automatically transforms JSON data for you, thereby avoiding the two-step process of making a .fetch() request and then a second call to the .json() method on the response

3.3 Making Requests & Handling Response via Axios

Making an HTTP request is as easy as passing a config object to the Axios function. In its simplest form, the object must have a URL property; if no method is provided, GET will be used as the default value.

Once an HTTP request is made, Axios returns a promise that is either fulfilled or rejected, depending on the response from the backend service. To handle the result, you can use the then() method, handle error use catch().

// send a GET request

axios({

method: 'get',

url: 'https://jsonplaceholder.typicode.com/todos'

})

.then(res => console.log(res))

.catch(error => console.error(error)); // shorthand way

axios.get('https://jsonplaceholder.typicode.com/todos')

.then(res => console.log(res))

.catch(error => console.error(error));

}

3.4 Simultaneous Requests

One of Axios’ more interesting features is its ability to make multiple requests in parallel by passing an array of arguments to the axios.all() method. This method returns a single promise object that resolves only when all arguments passed as an array has resolved. Here’s a simple example:

// execute simultaneous requests using axios.all()

axios.all([

axios.get("https://jsonplaceholder.typicode.com/todos?_limit=5"),

axios.get("https://jsonplaceholder.typicode.com/posts?_limit=5")

])

.then((res) => {

console.log(res[0]);

console.log(res[1]);

})

.catch((error) => console.error(error));

} // cleaner way using axios.spread()

axios.all([

axios.get("https://jsonplaceholder.typicode.com/todos?_limit=5"),

axios.get("https://jsonplaceholder.typicode.com/posts?_limit=5")

])

.then(axios.spread(todos, posts) => console.log(posts))

.catch((error) => console.error(error));

};

3.5 Intercepting Requests and Responses

You can examine and change HTTP requests from your program to the server and vice versa, which is useful for a variety of implicit tasks, such as logging and authentication. Interceptors receive the entire response object or request config.

// declare a request interceptor

axios.interceptors.request.use(config => {

// perform a task before the request is sent

console.log('Request was sent');



return config;

}, error => {

// handle the error

return Promise.reject(error);

});

References

https://www.sitepoint.com/axios-beginner-guide/

https://www.youtube.com/watch?v=6LyagkoRWYA

https://www.storyblok.com/tp/how-to-send-multiple-requests-using-axios