How to usethe XMLHttpRequest object in Javascript
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();
Above syntax is used to create an XMLHttpRequest object. This object has many different methods used to interact with the server to send, receive or interrupt responses from the server. In the response, we get a string from the server that we print.
Example: In this example, we will use the XMLHttpRequest object to make an Ajax call.
function run() {
// Creating Our XMLHttpRequest object
let xhr = new XMLHttpRequest();
// Making our connection
let url = 'https://jsonplaceholder.typicode.com/todos/1';
xhr.open("GET", url, true);
// function execute after request is successful
xhr.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
}
// Sending our request
xhr.send();
}
run();
Output:
"{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}"
How to make ajax call from JavaScript ?
Ajax is a powerful tool in web development for asynchronous communication with servers. With Ajax, you can fetch data from the server and update your webpage without interrupting what your user sees. It’s a basic concept in programming.
In this article, we’ll learn about three ways to make Ajax calls in JavaScript:
- Using the XMLHttpRequest object
- Using jQuery
- Using fetch() API
We’ll walk through each method with simple examples to help you understand how to use them in your projects.
Contact Us