Four ways making a request to a server in Ajax programming

In this post, we're gonna take a look at 4 different ways for making a request to a server in ajax programming. Each method has it pros and cons and depend on the context, we will choose the best fix for our application.

This post is organized into two parts, part one is about making GET requests and part two is about making POST requests. In each part, I'm gonna show you the minimal example of working code that you can copy and paste in your editor to see how each approach works in action.

1. GET request

This is an API that return a list of users: https://reqres.in/api/users

Our job is making a request and get the list and display on screen

1.1. XMLHttpRequest

First, let's take a look at the most basic way for achieving that, which is using XMLHttpRequest Following this guidance XHR#onload Three steps:

  1. Creating an XMLHttpRequest object
  2. Opening a URL
  3. Sending a request

Here is how the code looks like:

<!DOCTYPE html>
<html>
  <body>
    <div>
      <ol id="list">
      </ol>
    </div>
    <script>
      const list = document.getElementById('list')
      const method = 'GET';
      const url = 'https://reqres.in/api/users';
        
      var xhr = new XMLHttpRequest();
      xhr.open(method, url);
      xhr.responseType = 'json' //default is text
      xhr.onload = function () {
        xhr.response.data.forEach(element => {
          const li = document.createElement('li');
          li.innerText = element.email
          list.appendChild(li)
        });
      };
      xhr.send()
    </script>
  </body>
</html>

1.2. Fetch API

The second way making request is using Fetch API. Following this guidance Using Fetch

Here is how the code looks like:

<!DOCTYPE html>
<html>
  <body>
    <div>
      <ol id="list">
      </ol>
    </div>
    <script>
      const list = document.getElementById('list')
      const method = 'GET';
      const url = 'https://reqres.in/api/users';
        
      fetch(url).then(response => {
        return response.json()
      }).then(json => {
        console.log(json)
        json.data.forEach(element => {
          const li = document.createElement('li');
          li.innerText = element.email
          list.appendChild(li)
        });
      })
    </script>
  </body>
</html>

1.3. Axios

The third way is using a library called axios, which is the most popular one

<!DOCTYPE html>
<html>
  <body>
    <div>
      <ol id="list">
      </ol>
    </div>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script>
      const list = document.getElementById('list')
      const url = 'https://reqres.in/api/users';
        
      axios.get(url).then(response => {
        response.data.data.forEach(element => {
          const li = document.createElement('li');
          li.innerText = element.email
          list.appendChild(li)
        });
      })
    </script>
  </body>
</html>

1.4. jQuery

The fourth way is using jQuery, the code might look like this:

<!DOCTYPE html>
<html>
<body>
  <div>
    <ol id="list">
    </ol>
  </div>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"></script>
  <script>
    const list = document.getElementById('list')
    const url = 'https://reqres.in/api/users';

    $.get(url, response => {
      response.data.forEach(element => {
        const li = document.createElement('li');
        li.innerText = element.email
        list.appendChild(li)
      });
    })
  </script>
</body>
</html>

2. POST request

This is the url: https://reqres.in/api/register

And our job is to send POST request to that link and receive a response.

2.1. XMLHttpRequest

First, let's do it with XMLHttpRequest. The code might looks like this:

<!DOCTYPE html>
<html>
  <body>
    <script>
      const xhr = new XMLHttpRequest();
      const url = 'https://reqres.in/api/register';
      const method = 'POST';
      xhr.open(method, url)
      xhr.setRequestHeader('Content-Type', 'application/json')
      xhr.onload = function () {
        console.log(xhr.response)
      }
      const data = {
        email: "[email protected]",
        password: "pistol"
      }
      xhr.send(JSON.stringify(data))
    </script>
  </body>
</html>

2.2. Fetch API

Second, using Fetch API

<!DOCTYPE html>
<html>
  <body>
    <script>
      const url = 'https://reqres.in/api/register';
      const data = {
        email: "[email protected]",
        password: "pistol"
      }
      fetch(url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
      })
        .then(response => response.json())
        .then(response => {
          console.log(response)
        })
    </script>
  </body>
</html>

2.3. Axios

Third, using Axios

<!DOCTYPE html>
<html>
  <body>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script>
      const url = 'https://reqres.in/api/register';
      const data = {
        email: "[email protected]",
        password: "pistol"
      }
      axios.post(url, data).then(response => {
        console.log(response.data)
      })
    </script>
  </body>
</html>

2.4. jQuery

Fourth, using jQuery

<!DOCTYPE html>
<html>
  <body>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"></script>
    <script>
      const url = 'https://reqres.in/api/register';
      const data = {
        email: "[email protected]",
        password: "pistol"
      }
      $.post(url, data).then(response => {
        console.log(response)
      })
    </script>
  </body>
</html>

3. Conclusion

In conclusion, according to my own experience working in web development, axios is the best choice for making requests to a server. You can see people recommend using it all over the places for good reasons. However, knowing about other alternatives is also a good thing, not for using a better technique, but for appreciating the convenience that the axios brings. At the end of the day, it's all about making our developer's lives easier.

Hopefully, this post give you a big picture of the popular techniques using in communication between client & server and also a reference for those.