Logo

dev-resources.site

for different kinds of informations.

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

Published at
10/22/2024
Categories
xhr
axios
jquery
ajax
Author
khalifalmahmud0
Categories
4 categories in total
xhr
open
axios
open
jquery
open
ajax
open
Author
15 person written this
khalifalmahmud0
open
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>[email protected]</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>[email protected]</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: "[email protected]",
};

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: "[email protected]",
};

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: "[email protected]",
};

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: "[email protected]",
};

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: "[email protected]",
};

$.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: "[email protected]",
};

$.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!

jquery Article's
30 articles in total
Favicon
Reading Progress Bar
Favicon
Add Row (Clone)
Favicon
Make PDF to Images converter in html, css, and, java, bootstrap and jquery
Favicon
$( "#x" ).prop( "checked", false ) is not working
Favicon
5 Top Libraries Each Frontend Developer Must Know
Favicon
Ditch the jQuery Crutch and Embrace Vanilla JS 👨🏽‍💻
Favicon
Level Up Your Web Development: Why You Should Ditch jQuery for Vanilla JavaScript
Favicon
Why Does jQuery or a DOM Method Like `getElementById` Fail to Find an Element?
Favicon
SimpleTimepickerRB: A Lightweight and Customizable Timepicker Plugin for jQuery
Favicon
A Comprehensive Guide with XHR, Fetch API, Axios and jQuery AJAX
Favicon
Unleash Your Web Development Skills with the 'Quick Start with jQuery' Course
Favicon
Building a One-Page CRUD Application with Laravel and jQuery
Favicon
Here's How I implement cursor-based pagination in jQuery Datatable.
Favicon
Using jQuery
Favicon
HeatColor UDF (based on jQuery library)
Favicon
Jquery select2 css height problem fixed
Favicon
Why jQuery Exists
Favicon
Scientific problems are not real problems for programmers
Favicon
Master jQuery.each() with These 5 Essential Examples
Favicon
Master jQuery.each() with These 5 Essential Examples
Favicon
Total.js UI :Two Beginner Projects to understand Paths and Data Binding
Favicon
Implementing Infinite Scroll with Laravel and jQuery
Favicon
jQuery vs React – Which One Is Better For Your Project?
Favicon
Tutorial Menggunakan jQuery pada WordPress dengan benar
Favicon
Uncovering the Magic: 10 Fascinating Facts About jQuery
Favicon
Asynchronous Requests in JavaScript: AJAX, JQUERY, FETCH and AXIOS.
Favicon
jQuery's Role in Modern Web Development: Beginnings, 2024, and Beyond
Favicon
Vanilla JS Effect Methods
Favicon
Common JavaScript "event Handler" Mistake
Favicon
Recommended Project: Implement User Login Function

Featured ones: