javascript

Working With XMLHttpRequest

The XMLHttpRequest is a Javascript object that is used to interact with web servers.

The XMLHttpRequest() is a Javascript function that makes it possible for developers to fetch XML data from the database without reloading the entire page.

Now, XMLHttpRequest is not just limited to XML alone. It can be used to retrieve any type of data, especially from an API.

Let us see an example of how it works.

let xhr = new XMLHttpRequest(); //Invoke an instance
xhr.onload = success; //call success function
xhr.onerror = error; //call error function
xhr.open('GET',' fetch('https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits'); //initiate a request
xhr.send(); //send the request

//Handle success
function success(){
let data = JSON.parse(this.responseText);
console.log(data);
}

//Handle error
function error(err){
console.log(`Request failed: ${err}`);
}

Result:

Recent Posts

Perks of Being a Copy-Paste Developer

Why borrowing code is a skill—when you understand what you're copying. For years, "copy-paste developer"…

1 day ago

Conditionally Disable an Input Field Using React Hook Form

Interactive forms rarely keep every field active all the time. Sometimes an input should only…

1 day ago

JavaScript Temporal API

A modern JavaScript API for working with dates, times, time zones, and calendars without the…

4 days ago

Node.js Under the Hood

Understanding What Happens Behind the Scenes Node.js looks simple from the outside—you write JavaScript, call…

4 days ago

This is How You Cultivate Negative Capability

The need for absolute certainty is the greatest disease the engineering mind faces. The moment…

6 days ago

You Don’t have to become the World’s Greatest Programmer.

The software industry is one of the most competitive places to build a career. Every…

1 week ago