受欢迎的博客标签

5 AJAX libraries for fetching data from the server

Published

AJAX is a set of web development techniques used by client-side frameworks and libraries to make asynchronous HTTP calls to the server. AJAX stands for Asynchronous JavaScript and XML. AJAX used to be a common name in the web development circles and many of the popular JavaScript widgets were built using AJAX. For instance, a particular user interaction such as a button press would invoke an asynchronous call to the server and the server would retrieve data and return it back to the client—all this without reloading the webpage.

A Modern Reintroduction to AJAX

JavaScript has evolved and, today, we have dynamic websites built using front-end libraries and/or frameworks like React, Angular, Vue, etc. The concept of AJAX has also undergone major changes because modern asynchronous JavaScript calls involve retrieving JSON instead of XML. There are many libraries out there that let you make asynchronous calls to the server from your client-side application. Some of them have made their way into the browser standards, whereas others have a large user-base because they are flexible and easy to use. Some of them support promises whereas others use callbacks. In this article, I’ve covered the top 5 AJAX libraries for fetching data from the server.

Fetch API

Fetch API is the modern alternative to XMLHttpRequest for retrieving resources from the server. Unlike XMLHttpRequest, it has a more powerful feature set and a more meaningful name. Fetch is also flexible and easy to use because of its syntax and structure. However, the thing that sets it apart from other AJAX HTTP libraries is that it is supported by all modern web browsers. Fetch follows a request-response approach where Fetch makes a request and returns a promise that resolves to the Response object.

You can pass a Request object to fetch or, alternatively, just the URL of the resource to be fetched. The example below demonstrates a simple GET request made with Fetch.

 
fetch('https://www.example.com', {
 
        method: 'get'
 
    })
 
    .then(response => response.json())
 
    .then(jsonData => console.log(jsonData))
 
    .catch(err => {
 
            //error block
 
        }
 

As you can see, Fetch’s then method returns a response object that you can further manipulate using a chain of thens. I’ve used the .json() method to transform the response to JSON and print it to the console.

What if you need to POST the form data or create an AJAX file upload using Fetch? Apart from Fetch, you will need an input form, and the FormData library to store the form object.

 
var input = document.querySelector('input[type="file"]')
 
 
 
var data = new FormData()
 
data.append('file', input.files[0])
 
data.append('user', 'blizzerand')
 
 
 
fetch('/avatars', {
 
    method: 'POST',
 
    body: data
 
})
 

You can read more about Fetch API in the official Mozilla web docs.

Axios

Axios is a modern JavaScript library built on top of XMLHttpRequest for making AJAX calls. It lets you make HTTP requests from both the browser and the server. Additionally, it supports the Promise API that is native to ES6. Other prominent features of Axios include:

  • Intercept requests and responses.

  • Transform request and response data using promises.

  • Automatically transforms JSON data.

  • Cancel live requests.

To use Axios, you will need to install it first.

 
npm install axios
 

Here is a basic example that demonstrates Axios in action.

 
// Make a request for a user with a given ID
 
axios.get('/user?ID=12345')
 
  .then(function (response) {
 
    console.log(response);
 
  })
 
  .catch(function (error) {
 
    console.log(error);
 
  });
 

Axios has an easier syntax compared to that of Fetch. Let’s do something more complex like the AJAX file uploader that we built earlier using Fetch.

 
 var data = new FormData();
 
   data.append('foo', 'bar');
 
   data.append('file', document.getElementById('file').files[0]);
 
 
 
   var config = {
 
        onUploadProgress: function(progressEvent) {
 
          var percentCompleted = Math.round( (progressEvent.loaded * 100) / progressEvent.total );
 
        }
 
    };
 
 
 
    axios.put('/upload/server', data, config)
 
      .then(function (res) {
 
        output.className = 'container';
 
        output.innerHTML = res.data;
 
      })
 
      .catch(function (err) {
 
        output.className = 'container text-danger';
 
        output.innerHTML = err.message;
 
      });
 

Axios is definitely more readable. Axios is also popular with modern libraries such as React and Vue.

jQuery

jQuery used to be a front-line library in JavaScript for everything from making AJAX calls to manipulating the contents of the DOM. Although its relevance has partially diminished after the onset of other front-end libraries, you can still use jQuery for making asynchronous calls.

If you’ve used jQuery before, this would probably be the easiest solution of the lot. However, you would have to import the whole jQuery library for using the $.ajax methods. Although the library has domain-specific methods such as $.getJSON, $.getand $.post, the syntax isn’t as easy as other AJAX libraries out there. Here is the code for making a basic GET request.

 
$.ajax({
 
  url: '/users',
 
  type: "GET",
 
  dataType: "json",
 
  success: function (data) {
 
      console.log(data);
 
  }
 
  fail: function () {
 
      console.log("Encountered an error")
 
  }
 
});
 

The good thing about jQuery is that you will find tons of support and documentation if you’re in doubt. I found many examples for AJAX file upload using FormData() and jQuery. Here is the easiest approach:

 
var formData = new FormData();
 
formData.append('file', $('#file')[0].files[0]);
 
 
 
$.ajax({
 
       url : 'upload.php',
 
       type : 'POST',
 
       data : formData,
 
       processData: false,  // tell jQuery not to process the data
 
       contentType: false,  // tell jQuery not to set contentType
 
       success : function(data) {
 
           console.log(data);
 
           alert(data);
 
       }
 
});
 

SuperAgent

SuperAgent is a lightweight and progressive AJAX library that’s focused more on readability and flexibility. SuperAgent also boasts of a gentle learning curve unlike other libraries out there. It has a module for Node.js with the same API. SuperAgent has a request object that accepts methods such as GET, POST, PUT, DELETE, and HEAD. You can then call .then().end() or the new .await()method to process the response. For example, here is a simple GET request with SuperAgent.

 
 request
 
   .post('/api/pet')
 
   .send({ name: 'Manny', species: 'cat' })
 
   .set('X-API-Key', 'foobar')
 
   .set('Accept', 'application/json')
 
   .then(function(res) {
 
      alert('yay got ' + JSON.stringify(res.body));
 
   });
 

What if you wanted to do something more such as uploading a file using this AJAX library? That’s super easy too.

 
 request
 
   .post('/upload')
 
   .field('user[name]', 'Tobi')
 
   .field('user[email]', '[email protected]')
 
   .field('friends[]', ['loki', 'jane'])
 
   .attach('image', 'path/to/tobi.png')
 
   .then(callback);
 

If you’re interested in knowing more about SuperAgent, they have a good set of documentation to get you started.

Request - A Simplified HTTP Client

The Request library is one of the simplest ways to make HTTP calls. The structure and syntax are very similar to that of how requests are handled in Node.js. Currently, the project has 18K stars on GitHub and deserves a mention for being one of the popular HTTP libraries available. Here is an example:

 
var request = require('request');
 
request('http://www.google.com', function (error, response, body) {
 
  console.log('error:', error); // Print the error if one occurred
 
  console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
 
  console.log('body:', body); // Print the HTML for the Google homepage.
 
});
 

Conclusion

Making HTTP calls from the client-side wasn’t this easy a decade ago. A front-end developer would have to rely on XMLHttpRequest which was hard to use and implement. The modern libraries and HTTP clients make the front-end features like user interactions, animations, asynchronous file uploads, etc., easier. 

My personal favorite is Axios because I personally feel it’s more readable and easy on the eyes. You can also stick to Fetch because it’s well documented and a standardized solution.

What is your personal favorite AJAX library? Share your thoughts below.