Search

Programming
Programming

We provide developers and engineers the guides and tutorials they...

Content
Content

Content is king. It's not just about how you're going to write, b...

Events
Events

Looking for an engaging connection with thousands of other people...

How to make an HTTP request in Javascript?

How to make an HTTP request in Javascript?

HTTP requests can be used to send or receive data from a server side resource. In this expert-series article, we'll cover the XMLHttpRequest and fetch API to make HTTP requests in JavaScript.

Introduction

JavaScript is a cross-platform, object-oriented scripting language used to make webpages interactive, mainly used as a frontend technology for building webpages and apps. 

Also Read: Understanding JavaScript For Loops

The interaction between the frontend and backend of websites is made possible through HTTP requests. Functionalities like updating a record in the database, creating a new record, deleting a picture, and so on, all require an interaction between a server and a client to modify data.

HTTP requests can be used to send or receive data from a server side resource. In this snippet, we'll cover the XMLHttpRequest and fetch API to make HTTP requests in JavaScript.

Also Read: JavaScript Array Map method

Here's an example using XMLHttpRequest

var xhr = new XMLHttpRequest(); 
xhr.open("GET", "https://api.example.com/data.json", true); 
xhr.onreadystatechange = function() { if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) { console.log(xhr.responseText); } }; 
xhr.send();

And here's an example using fetch API

Also Read: Best Youtube channels to Learn JavaScript

fetch("https://api.example.com/data.json")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
TWT Staff

About author

Writes about Programming, tech news, discuss programming topics for web developers (and Web designers), and talks about SEO tools and techniques

View all posts (402)
Your experience on this site will be improved by allowing cookies Cookie Policy