Updated April 3, 2023
Introduction to JavaScript Request
JavaScript Request function is used to exchange data from server-side resources. The request function sends and receives data from the server by making HTTP requests. These requests are performed along with a fetch function to get a response. These terminologies ‘Request’, ‘fetch’, and ‘Response’ are replacements for ‘XMLHTTPRequest’. Internet, which is made up of the number of servers that are interconnected computers, browsing the web ad navigating through the pages is the same as you are requesting the browser to send you the information from the servers. In this article, we shall look at a few ways to send JavaScript Request functions.
Syntax of JavaScript Request
Below is the syntax mentioned:
var request = new Request(sample_url: String, [init: Object]);
- sample_url: It contains the direct URL of the response you want to fetch from the request is the object creates a copy,
- init: Object, can contain custom settings to apply for a request. Some of the possible options listed below:
- method: We have two request methods, ‘GET’, ‘DELETE’ and ‘POST’, the default being ‘GET.’
- body: ‘Blob’, ‘FormData’, ‘ReadableStream’, or anybody you want to add to the request.
- mode: Request mode like ‘cors’, ‘no-cors’, or ‘navigate’. Default being ‘cors’.
- cache: mode of cache used for the request.
- credentials: Credentials that are sent to use for the request. ‘omit’, ‘same-origin’. Default being ‘same-origin’.
- redirect: modes used for the request: error, follow, or manual. Default being ‘follow’.
- integrity: Involves subresource integrity value for the request.
- referrer: default referrer being about:client
- headers: the key-value object of HTTP headers to be set
Difference between GET and POST:
- GET request is simpler and faster than the POST method.
- POST requests are used to update a file or a database on the server.
- POST is also used to send a large amount of data with no size limitations
- POST method is far more robust and secure than the GET method; input may contain unknown characters.
Examples of JavaScript Request
Given below are the examples of JavaScript Request:
Example #1
JavaScript Request fetch() method to get the IP address of the machine. Code:
<!DOCTYPE html>
<html>
<head>
<title>Display IP Address</title>
<h2> Using fetch method to get the JavaScript request</h2>
<style>
body {
background-color: #CCBBFF;
}
h1 {
font-family: sans-serif;
text-align: center;
padding-top: 40px;
font-size: 40px;
margin: -10px;
}
p {
font-family: sans-serif;
color: #000000;
text-align: center;
}
</style>
</head>
<body>
<h1 id=ipAddress></h1>
<p>( The above is the IP Address of your machine )</p>
<script>
fetch("https://ipinfo.io/json")
.then(function (response) {
return response.json();
})
.then(function (ipJson) {
document.querySelector("#ipAddress").innerHTML = ipJson.ip;
})
.catch(function (error) {
console.log("Error: " + error);
});
</script>
</body>
</html>
Output: To ensure security, we are hiding the IP address.
Fetch() method will fetch the IP address of the machine from URL ‘https://ipinfo.io/json’.
Example #2
Using XMLHTTPRequest of JavaScript Request function to get the IP. Above example uses fetch() method, here we are using XMLHTTPRequest().
Code:
<!DOCTYPE html>
<head>
<title>Display IP Address</title>
<h2> Using XMLHTTPRequest method to get the JavaScript request</h2>
<style>
body {
background-color: #CCBBFF;
}
h1 {
font-family: sans-serif;
text-align: center;
padding-top: 40px;
font-size: 40px;
margin: -10px;
}
p {
font-family: sans-serif;
color: #000000;
text-align: center;
}
</style>
</head>
<body>
<h1 id=ipAddress></h1>
<p>( The above is the IP Address of your machine )</p>
<script>
let IPxhr = new XMLHttpRequest();
IPxhr.open('GET', "https://ipinfo.io/json", true);
IPxhr.send();
IPxhr.onreadystatechange = processRequest;
function processRequest(e) {
if (IPxhr.readyState == 4 && IPxhr.status == 200) {
let response = JSON.parse(IPxhr.responseText);
document.querySelector("#ipAddress").innerHTML = response.ip;
}
}
</script>
</body>
</html>
Output:
Use an API testing tool to check the data coming from the URL ‘https://ipinfo.io/json’.
We are using the GET method to get the data; JSON has ‘ip’, ‘city’, ‘region’, ‘country’, ‘loc’, ‘org’, ‘postal’, timezone’, ‘readme’. We have displayed only the ip by using a response.ip.
Let us see How JavaScript Request functions work. But, first, we shall code some lines to get to know how the request functions are working.
Example #3
Code:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Request POST</title>
</head>
<script>
var request = new Request('/', {
method: 'POST',
body: 'This text will be posted on the console' });
request.blob().then(function(blob) {
var reader = new FileReader();
reader.onload = function() {
document.write(reader.result);
};
reader.readAsText(blob);
});
</script>
</html>
Output:
Example #4
JSON with the POST method
Code:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Request POST JSON</title>
</head>
<script>
var request = new Request('/', {
method: 'POST',
body: '{ "name": "Saideep", "age": 23, "city": "Vizag", "region": "India" }'
});
request.json().then(function(json) {
document.write(json.name + "<br />");
document.write(json.age+ "<br />");
document.write(json.city+ "<br />");
document.write(json.region+ "<br />");
});
</script>
</html>
Output:
Example #5
To get data from an asp page with values being passed as fname and lname to .asp page.
Code:
<!DOCTYPE html>
<html>
<body>
<h2>The JavaScript Request Object</h2>
<button type="button" onclick="loadData()">Request data</button>
<p id="data"></p>
<script>
function loadData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
document.getElementById("data").innerHTML = this.responseText;
}
};
xhttp.open("GET", "demo_get2.asp?fname=Karthick&lname=Reddy", true);
xhttp.send();
}
</script>
</body>
</html>
Output:
Values fname and lname are sent to the .asp file, and the above button retrieves the data from the .asp page.
Conclusion
With this, we can conclude our topic for the day, ‘JavaScript Request’. First, we have seen what JavaScript Request methods are and have also listed out a few. Next, we have gone through examples using the fetch() method, XMLHTTPRequest() method, and finally, the JavaScript Request method to get a differentiation on all of those. Writing code that can make an HTTP request and returning data is one of the easiest things to do in JavaScript. Most of the data you see on the websites results from requests hitting the server and fetching the API response. I hope this article has put you on good notes.
Recommended Articles
This is a guide to JavaScript request. Here we discuss the Examples of Javascript Event Listener along with the codes and outputs. You may also have a look at the following articles to learn more –