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) opera…


This content originally appeared on DEV Community and was authored by Khalif AL Mahmud

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);
  • 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();
  • 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);
  • 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();

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);
 });
  • 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);
 });
  • 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);
 });
  • 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);
 });

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);
 });
  • 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);
 });
  • 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);
 });
  • 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);
 });

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);
 },
});
  • 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);
 },
});
  • 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);
 },
});
  • 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);
 },
});

Happy coding!


This content originally appeared on DEV Community and was authored by Khalif AL Mahmud


Print Share Comment Cite Upload Translate Updates
APA

Khalif AL Mahmud | Sciencx (2024-10-22T09:11:41+00:00) A Comprehensive Guide with XHR, Fetch API, Axios and jQuery AJAX. Retrieved from https://www.scien.cx/2024/10/22/a-comprehensive-guide-with-xhr-fetch-api-axios-and-jquery-ajax/

MLA
" » A Comprehensive Guide with XHR, Fetch API, Axios and jQuery AJAX." Khalif AL Mahmud | Sciencx - Tuesday October 22, 2024, https://www.scien.cx/2024/10/22/a-comprehensive-guide-with-xhr-fetch-api-axios-and-jquery-ajax/
HARVARD
Khalif AL Mahmud | Sciencx Tuesday October 22, 2024 » A Comprehensive Guide with XHR, Fetch API, Axios and jQuery AJAX., viewed ,<https://www.scien.cx/2024/10/22/a-comprehensive-guide-with-xhr-fetch-api-axios-and-jquery-ajax/>
VANCOUVER
Khalif AL Mahmud | Sciencx - » A Comprehensive Guide with XHR, Fetch API, Axios and jQuery AJAX. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/10/22/a-comprehensive-guide-with-xhr-fetch-api-axios-and-jquery-ajax/
CHICAGO
" » A Comprehensive Guide with XHR, Fetch API, Axios and jQuery AJAX." Khalif AL Mahmud | Sciencx - Accessed . https://www.scien.cx/2024/10/22/a-comprehensive-guide-with-xhr-fetch-api-axios-and-jquery-ajax/
IEEE
" » A Comprehensive Guide with XHR, Fetch API, Axios and jQuery AJAX." Khalif AL Mahmud | Sciencx [Online]. Available: https://www.scien.cx/2024/10/22/a-comprehensive-guide-with-xhr-fetch-api-axios-and-jquery-ajax/. [Accessed: ]
rf:citation
» A Comprehensive Guide with XHR, Fetch API, Axios and jQuery AJAX | Khalif AL Mahmud | Sciencx | https://www.scien.cx/2024/10/22/a-comprehensive-guide-with-xhr-fetch-api-axios-and-jquery-ajax/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.