Where knowledge empowers you to understand your world

How To Send A GET Request In JavaScript

By Nicholas Brown – Follow me on X.

You can send a GET request from your JavaScript app or send it from a web page using XMLHttpRequest, which is a JavaScript class. This HTTP GET request can be used to retrieve data from an API so that you can incorporate it in your web page, or to load pages from your website’s own database and insert them into a web page in real time.

To send a GET request in JavaScript, you would first need to create an XMLHttpRequest object. The next step is to get the URL of the API endpoint you want to get data from. In this example, it will be ‘https://www.boredapi.com/api/activity’. That is where you will send your request.

Don’t worry about the random content in the response, this is just to enable you to test your code without having to sign up for an API. However, you can create your own server to test this code as well.

Note that HTTP GET requests are not meant for submitting data to servers. They serve the purpose of getting data from a server for use in your app or website. If you want to submit data to a server, you can use a POST request.

For the sake of clarity, the code sample herein is an HTML file with the JavaScript embedded. In production, it is best to place the JavaScript in a separate file to neaten your code.

JavaScript GET Request Example: Sending A GET Request With JavaScript

The code sample below will also send a GET request from an HTML page.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript">
const url = "https://www.boredapi.com/api/activity";
let request = new XMLHttpRequest();
let newParagraph = document.createElement("p");

request.onreadystatechange = function() {
if (request.readyState === 4 && request.status === 200) {
let apiresponse = request.responseText;
let text = document.createTextNode(apiresponse);
newParagraph.appendChild(text);
newParagraph.innerText = apiresponse;
document.body.appendChild(newParagraph);
}
};
request.open("GET", url, true);
request.send(null);
</script>
</head>
<body>

</body>
</html>

Notes:

Change the ‘url’ variable to whichever API endpoint you want to send the GET request to.

The line ‘if (request.readyState === 4 && request.status === 200)’ checks to see if the server responded with a ‘200’ status code. That status code means everything is ok and the server found what you are looking for. Learn more about HTTP status codes.

The section starting with ‘let apiresponse = request.responseText;’ and ending with ‘document.body.appendChild(newParagraph);’ creates a text node containing the server’s response and then adds it to a paragraph in the body of the HTML file.

Further Reading

How To Send A POST Request From An HTML Page Using JavaScript

Understanding Conditional Statements In JavaScript

Leave a Reply