Sending AJAX Requests in JavaScript

There are two ways to make AJAX calls in the browser with JavaScript: the XMLHttpRequest object and Fetch API, and several client libraries such as jQuery, Axios, and SuperAgent that use one of these two methods. The XMLHttpRequest() method is the oldest and most popular way to send AJAX requests to a server in JavaScript. The Fetch API is a new, more flexible, and easier way to make asynchronous HTTP requests to a server and is based on JavaScript Promises. To send AJAX requests to Node.js, you can use the built-in http module. In this JavaScript AJAX Request Example, we use the XMLHttpRequest() method to send asynchronous HTTP requests to the ReqBin echo URL. Click Execute to run JavaScript AJAX Request Example online and see the result.
Sending AJAX Requests in JavaScript Execute
let xhr = new XMLHttpRequest();

let url = "https://reqbin.com/echo/get/json";

xhr.open("GET", url);

xhr.send();

xhr.onload = () => console.log(xhr.responseText);
Updated: Viewed: 10608 times

What is JavaScript?

JavaScript is a scripting language that works both on the client-side (in browsers) and on the server-side (Node.js), making it a universal tool for developing applications for different devices and platforms using almost the same technology stack. JavaScript is the primary programming language for the web that turns static web pages into interactive ones. Using JavaScript, you can modify the page's HTML code and CSS styles, calculate and process data, validate forms, play videos, etc.

What is Ajax?

Ajax (Asynchronous Javascript and XML) is an approach to creating interactive user interfaces for web applications using "background" communication between a browser and a web server. Ajax is often used in Single Page Applications (SPA). Web applications use Ajax to send data to the server and receive data from the server without reloading the entire page. Ajax makes web applications interactive, convenient, and fast.

How to send Ajax request with XMLHttpRequest?

XMLHttpRequest (XHR) is a built-in JavaScript object that allows a web page to make a request to the server and receive a response without reloading the entire page. Using the XMLHttpRequest() method allows a web developer to render and replace part of the page with data received from the server without re-requesting the entire page. Below is an Ajax example sending JSON to the ReqBin echo URL with XMLHttpRequest object:

JavaScript POST Request with XMLHttpRequest Example
let xhr = new XMLHttpRequest();
xhr.open("POST", "https://reqbin.com/echo/post/json");

xhr.setRequestHeader("Content-Type", "application/json");

xhr.onload = () => console.log(xhr.responseText);

let data = `{
  "Id": 78912,
  "Customer": "Jason Sweet",
}`;

xhr.send(data);

How to send Ajax request with Fetch API?

The Fetch API introduces a new global fetch() method that allows you to make HTTP requests similar to XMLHttpRequest (XHR) to get resources from the server. Unlike XMLHttpRequest, the Fetch API is based on promises, making the code concise and straightforward. The difference between the Fetch API and other Ajax HTTP libraries is that all modern browsers natively support the Fetch API and do not require additional libraries. Fetch API follows a request-response approach in which Fetch makes a request and returns a promise that resolves to a Response object. Below is an example of submitting an Ajax request to the ReqBin echo URL with Fetch API:

JavaScript Fetch API Request Example
fetch('https://reqbin.com/echo/get/json')
   .then(response => response.text())
   .then(text => console.log(text))

Benefits of using the Fetch API:

  • Fetch API is flexible and easy to use
  • The Fetch API is promise-based, which avoids nested callbacks.
  • Fetch API supported by all modern browsers
  • Fetch API follows the "request-response" principle

Disadvantages of using Fetch API:

  • Fetch API does not send cookies by default
  • In Fetch API CORS is disabled by default

How to send Ajax request with jQuery?

jQuery is a client-side library. It is free and powerful, relatively easy to set up and learn, and has several extensions and plugins available for everything. jQuery has a large community where you can find answers to many questions and get ready-made solutions. The ajax() method is used in jQuery to make Ajax calls. jQuery provides several methods for sending AJAX requests, such as $.post(), $.get() and $.ajax(). Below is an example of submitting an Ajax request to the ReqBin echo URL using jQuery:

JavaScript POST request with jQuery Ajax
$.ajax({
  type: "POST",
  url: "https://reqbin.com/echo/post/json",
  data: `{
    "Id": 78912,
    "Customer": "Jason Sweet",
  }`,
  success: function (result) {
     console.log(result);
  },
  dataType: "json"
});

Benefits of using the jQuery:

  • jQuery is simple, flexible, and expandable
  • jQuery is open source, which means rapid growth and developer freedom

Disadvantages of using jQuery:

  • jQuery is slower compared to vanilla JavaScript

How to send Ajax request with Axios?

Axios is one of the most popular promise-based HTTP clients available that works both on the client-side (in browsers) and on the server-side (NodeJ). Axios provides a single API for working with XMLHttpRequest and the HTTP interface. Axios, like Fetch, supports promises for handling asynchronous requests. In addition, it binds requests using a polyfill for the new ES6 promise syntax. Below is an example of submitting an Ajax request to the ReqBin echo URL using Axios:

JavaScript Ajax request with Axios Example
axios.get("https://reqbin.com/echo/get/json")
  .then(response => {
    data = response.text
    console.log(data)
  })
  .catch(error => {
      console.log(error.message)
  })

Benefits of using the Axios:

  • Promises are supported by default in Axios.
  • Automatic transformations for JSON data
  • Built-in support on the client-side for protection against XSRF
  • Can capture requests or responses before they are completed
  • Can set a response timeout
  • Works on both Node.js and the browser

Disadvantages of using Axios:

  • The Axios library adds extra kilobytes to load while the Fetch API is built into the browser

How to send Ajax request with SuperAgent?

SuperAgent is a lightweight and progressive AJAX library that focuses more on readability and flexibility. The Superagent library, like Axios, is suitable for Node.js and modern browsers. It provides the developer with a simple and understandable API that is convenient to work with. Below is an example of submitting an Ajax request to the ReqBin echo URL using SuperAgent:

JavaScript Ajax request with SuperAgent Example
superagent
   .get('https://reqbin.com/echo/get/json')
   .then(text => console.log(text))

Benefits of using the SuperAgent:

  • SuperAgent is expandable
  • SuperAgent has a nice interface for making HTTP requests
  • SuperAgent supports chaining multiple calls to fulfill requests
  • SuperAgent works in Node.js environment and in browsers
  • SuperAgent supports progress indications for uploading and downloading data
  • SuperAgent supports the chunked transfer encoding mechanism

Disadvantages of using SuperAgent:

  • SuperAgent API doesn't follow standards.
  • SuperAgent library adds extra kilobytes to load while the Fetch API is built into the browser

See also