![]() |
VOOZH | about |
Making an Ajax call from JavaScript means sending an asynchronous request to a server to fetch or send data without reloading the web page. This allows dynamic content updates, enhancing user experience by making the web application more interactive and responsive.
There are multiple ways to make Ajax calls in JavaScript, but we will focus on three common approaches:
In this approach, we will use the XMLHttpRequest object to make an Ajax call. The XMLHttpRequest() method creates an XMLHttpRequest object which is used to make a request with the server.
Syntax
let xhttp = new XMLHttpRequest();It creates a new instance of the XMLHttpRequest object, used to send and receive data from a server asynchronously.
Output
"{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}"
In this example,
jQery simplifies the process of sending requests and receiving responses from a server without reloading the page. The ajax() method is a more flexible and reliable option compared to other older methods, allowing you to handle different types of requests (like GET or POST) and easily update the page content.
Syntax
$.ajax({arg1: value, arg2: value, ... });Output:
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}
In this example
The fetch() API is used to make requests to the server. Its flexible structure makes it easy to use. When a request is made, the server responds with a promise, which is then resolved into a string.
Syntax
fetch(url, {config}).then().catch();Output:
{ userId:1 ,id:1 ,title : "delectus aut autem" ,completed : false
__proto__:Object }
Title of our response : delectus aut autem
Ajax is a powerful tool that allows web pages to load content without refreshing the entire page, making websites faster and more interactive. In this article, we explored how to make Ajax calls using different methods like XMLHttpRequest, the modern fetch() API, and jQuery's ajax() method. By understanding these techniques, you can create dynamic web applications that provide a smoother experience for users.