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!

ajax Article's
30 articles in total
Favicon
How to Load More data using ajax pagination on scroll in laravel 11 Example
Favicon
Ajax: Revolutionizing Web Interaction - A Comprehensive Guide
Favicon
How to create ajax How to create ajax dependent dropdown in laravel 11
Favicon
A Comprehensive Guide with XHR, Fetch API, Axios and jQuery AJAX
Favicon
Vaadin, the battery-included server-side AJAX framework
Favicon
Augmenting the client with Alpine.js
Favicon
Augmenting the client with Vue.js
Favicon
A short history of AJAX and SSR
Favicon
Experimenting with AJAX and APIs: A Comprehensive Guide for Beginners
Favicon
Asynchronous Requests in JavaScript: AJAX, JQUERY, FETCH and AXIOS.
Favicon
JS: Geek Out with AJAX
Favicon
Exploring django-ajax: Simplifying AJAX Integration in Django
Favicon
Exploring The Power Of AJAX Flex In Web Development
Favicon
Laravel 11 Ajax Form Submit With Validation
Favicon
com.girl.brashcrab
Favicon
Some uncommon Ajax techniques that most people don't know
Favicon
A Simple Guide to Developing AJAX-Driven Plugins for WordPress
Favicon
Do you know AJAX?
Favicon
419 Page expired Laravel 10|9 postman, Ajax Post, Form Submit Login
Favicon
crud operation using ajax in laravel 10 with popup modal
Favicon
How do I get my text to connect to the ajax call I am trying to connect from the ajax call to the controller?
Favicon
Trending Tech: HTMX
Favicon
Send Form Data With Ajax
Favicon
Dependent Country State City Dropdown using jQuery Ajax in Laravel 10
Favicon
What is AJAX in JavaScript ?
Favicon
Laravel 10 Ajax Crop and Upload Image using Croppie js
Favicon
Laravel 10 Ajax CRUD with Image Upload Tutorial
Favicon
Tab Content Structure with Ajax and PHP
Favicon
Create a mini facebook clone in laravel and ajax
Favicon
How To Cancel an AJAX Request in JavaScript Using the AbortController

Featured ones: