JavaScript Request
Posted by Superadmin on May 02 2023 14:58:51

JavaScript Request

JavaScript Request

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]);

Difference between GET and POST:

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.

JavaScript request output 1

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:

JavaScript request output 2.1

Use an API testing tool to check the data coming from the URL ‘https://ipinfo.io/json’.

JavaScript request output 2.2

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:

JavaScript request output 3

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:

output 4

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:

output 5

output 5.2

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.