DEV Community

Khalif AL Mahmud
Khalif AL Mahmud

Posted on • Edited on

A Comprehensive Guide with XHR, Fetch API, Axios and jQuery AJAX

In this blog post, we’ll explore four commonly used JavaScript APIs for making HTTP requests: Fetch API, Axios, and jQuery AJAX. We’ll provide short examples for each of these APIs to demonstrate how to perform CRUD (Create, Read, Update, Delete) operations.

1. XMLHttpRequest (XHR):

A traditional JavaScript API for making asynchronous HTTP requests in web browsers, allowing interaction with servers and handling data in formats like XML or JSON.

  • Create: Create new data using XMLHttpRequest with the POST method and send XML data to the server, and handle the response to access the created data.
const createData =
 "<user><name>John Doe</name><email>john@example.com</email></user>";

const xhr = new XMLHttpRequest();
xhr.open("POST", "https://api.example.com/users", true);
xhr.setRequestHeader("Content-Type", "application/xml");

xhr.onload = function () {
 if (xhr.status >= 200 && xhr.status < 300) {
  console.log("User created successfully:", xhr.responseXML);
 } else {
  console.error("Error creating user:", xhr.status, xhr.statusText);
 }
};

xhr.onerror = function () {
 console.error("Error creating user:", xhr.status, xhr.statusText);
};

xhr.send(createData);
Enter fullscreen mode Exit fullscreen mode
  • Read: Fetch data from the server using XMLHttpRequest with the GET method, and handle the response to access the retrieved data.
const xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.example.com/users/123", true);

xhr.onload = function () {
 if (xhr.status >= 200 && xhr.status < 300) {
  console.log("User data:", xhr.responseXML);
 } else {
  console.error("Error fetching user data:", xhr.status, xhr.statusText);
 }
};

xhr.onerror = function () {
 console.error("Error fetching user data:", xhr.status, xhr.statusText);
};

xhr.send();
Enter fullscreen mode Exit fullscreen mode
  • Update: Update existing data by using XMLHttpRequest with the PUT method and sending XML data to the server with modified information, and handle the response to access the updated data.
const updateData =
 "<user><name>Jane Smith</name><email>jane@example.com</email></user>";

const xhr = new XMLHttpRequest();
xhr.open("PUT", "https://api.example.com/users/123", true);
xhr.setRequestHeader("Content-Type", "application/xml");

xhr.onload = function () {
 if (xhr.status >= 200 && xhr.status < 300) {
  console.log("User updated successfully:", xhr.responseXML);
 } else {
  console.error("Error updating user:", xhr.status, xhr.statusText);
 }
};

xhr.onerror = function () {
 console.error("Error updating user:", xhr.status, xhr.statusText);
};

xhr.send(updateData);
Enter fullscreen mode Exit fullscreen mode
  • Delete: Remove data from the server using XMLHttpRequest with the DELETE method, and confirm the successful deletion through the response.
const xhr = new XMLHttpRequest();
xhr.open("DELETE", "https://api.example.com/users/123", true);

xhr.onload = function () {
 if (xhr.status >= 200 && xhr.status < 300) {
  console.log("User deleted successfully.");
 } else {
  console.error("Error deleting user:", xhr.status, xhr.statusText);
 }
};

xhr.onerror = function () {
 console.error("Error deleting user:", xhr.status, xhr.statusText);
};

xhr.send();
Enter fullscreen mode Exit fullscreen mode

2. Fetch API:

A modern native JavaScript API for making asynchronous HTTP requests in browsers, featuring a simpler and more standardized interface compared to XHR, widely recommended for modern applications.

  • Create: Use the fetch() function with the POST method to create new data by sending a JSON payload to the server.
const createData = {
 name: "John Doe",
 email: "john@example.com",
};

fetch("https://api.example.com/users", {
 method: "POST",
 headers: {
  "Content-Type": "application/json",
 },
 body: JSON.stringify(createData),
})
 .then((response) => response.json())
 .then((data) => {
  console.log("User created successfully:", data);
 })
 .catch((error) => {
  console.error("Error creating user:", error);
 });
Enter fullscreen mode Exit fullscreen mode
  • Read: Fetch data using the fetch() function with the GET method, and handle the response as JSON to access the retrieved data.
fetch("https://api.example.com/users/123")
 .then((response) => response.json())
 .then((data) => {
  console.log("User data:", data);
 })
 .catch((error) => {
  console.error("Error fetching user data:", error);
 });
Enter fullscreen mode Exit fullscreen mode
  • Update: Use the fetch() function with the PUT method to update existing data by sending a JSON payload to the server with modified information.
const updateData = {
 name: "Jane Smith",
 email: "jane@example.com",
};

fetch("https://api.example.com/users/123", {
 method: "PUT",
 headers: {
  "Content-Type": "application/json",
 },
 body: JSON.stringify(updateData),
})
 .then((response) => response.json())
 .then((data) => {
  console.log("User updated successfully:", data);
 })
 .catch((error) => {
  console.error("Error updating user:", error);
 });
Enter fullscreen mode Exit fullscreen mode
  • Delete: Delete data from the server using the fetch() function with the DELETE method, which will remove the specified resource.
fetch("https://api.example.com/users/123", {
 method: "DELETE",
})
 .then((response) => {
  if (response.ok) {
   console.log("User deleted successfully.");
  } else {
   console.error("Error deleting user.");
  }
 })
 .catch((error) => {
  console.error("Error deleting user:", error);
 });
Enter fullscreen mode Exit fullscreen mode

3. Axios:

A popular, lightweight JavaScript library for making HTTP requests, offering a promise-based API and features like request interception and JSON data handling.

  • Create: Employ axios.post() to create new data by sending a JSON payload to the server, and handle the response to access the created data.
const createData = {
 name: "John Doe",
 email: "john@example.com",
};

axios
 .post("https://api.example.com/users", createData)
 .then((response) => {
  console.log("User created successfully:", response.data);
 })
 .catch((error) => {
  console.error("Error creating user:", error);
 });
Enter fullscreen mode Exit fullscreen mode
  • Read: Use axios.get() to fetch data from the server and handle the response to access the retrieved data.
axios
 .get("https://api.example.com/users/123")
 .then((response) => {
  console.log("User data:", response.data);
 })
 .catch((error) => {
  console.error("Error fetching user data:", error);
 });
Enter fullscreen mode Exit fullscreen mode
  • Update: Use axios.put() to update existing data by sending a JSON payload to the server with modified information, and handle the response to access the updated data.
const updateData = {
 name: "Jane Smith",
 email: "jane@example.com",
};

axios
 .put("https://api.example.com/users/123", updateData)
 .then((response) => {
  console.log("User updated successfully:", response.data);
 })
 .catch((error) => {
  console.error("Error updating user:", error);
 });
Enter fullscreen mode Exit fullscreen mode
  • Delete: Utilize axios.delete() to remove data from the server, and confirm the successful deletion through the response.
axios
 .delete("https://api.example.com/users/123")
 .then(() => {
  console.log("User deleted successfully.");
 })
 .catch((error) => {
  console.error("Error deleting user:", error);
 });
Enter fullscreen mode Exit fullscreen mode

4. jQuery AJAX:

Part of the jQuery library, it simplifies asynchronous HTTP requests in web applications, providing an easy-to-use API for AJAX operations.

  • Create: Use $.ajax() with the POST method to create new data by sending a JSON payload to the server, and handle the response to access the created data.
const createData = {
 name: "John Doe",
 email: "john@example.com",
};

$.ajax({
 url: "https://api.example.com/users",
 method: "POST",
 contentType: "application/json",
 data: JSON.stringify(createData),
 success: function (data) {
  console.log("User created successfully:", data);
 },
 error: function (error) {
  console.error("Error creating user:", error);
 },
});
Enter fullscreen mode Exit fullscreen mode
  • Read: Fetch data from the server using $.ajax() with the GET method, and handle the response to access the retrieved data.
$.ajax({
 url: "https://api.example.com/users/123",
 method: "GET",
 success: function (data) {
  console.log("User data:", data);
 },
 error: function (error) {
  console.error("Error fetching user data:", error);
 },
});
Enter fullscreen mode Exit fullscreen mode
  • Update: Use $.ajax() with the PUT method to update existing data by sending a JSON payload to the server with modified information, and handle the response to access the updated data.
const updateData = {
 name: "Jane Smith",
 email: "jane@example.com",
};

$.ajax({
 url: "https://api.example.com/users/123",
 method: "PUT",
 contentType: "application/json",
 data: JSON.stringify(updateData),
 success: function (data) {
  console.log("User updated successfully:", data);
 },
 error: function (error) {
  console.error("Error updating user:", error);
 },
});
Enter fullscreen mode Exit fullscreen mode
  • Delete: Use $.ajax() with the DELETE method to remove data from the server, and confirm the successful deletion through the response.
$.ajax({
 url: "https://api.example.com/users/123",
 method: "DELETE",
 success: function () {
  console.log("User deleted successfully.");
 },
 error: function (error) {
  console.error("Error deleting user:", error);
 },
});
Enter fullscreen mode Exit fullscreen mode

Happy coding!

Top comments (0)