How to Get Data From URL in JavaScript
In this article, we will learn and use various JavaScript functions useful to load data from URL to our webpage and perform further operations to that data accordingly.
Get Data From URL in JavaScript
There are multiple built-in and external functions in JavaScript to load data by using URL. That URL invokes an API request for a function created on the server-side and returns the data to respond to the request.
We can send a request with a different method type, but in this article, we will discuss the GET
method, which is mostly used to get data from the server-side to the client-side. There are multiple ways to make a GET
request in JavaScript listed below.
Fetch
method- XML Http Request
fetch()
Method
The fetch()
method is an advanced way to make a network request in JavaScript, and the latest browsers support it. We can use the fetch()
method to load data from the server by sending a request to the server without refreshing the webpage.
We can use the async await
method with a fetch
request to make a promise compactly. In all advanced browsers, Async
functions are supported.
Basic syntax:
let requestRsponse = fetch(url, [params])
<script>
async function funcRequest(url){
await fetch(url)
.then((response) => {
return response.json(); // data into json
})
.then((data) => {
// Here we can use the response Data
}).
.catch(function(error) {
console.log(error);
});
}
const url = 'URL of file';
funcRequest(url);
</script>
In the above JavaScript source, we have declared async await
function funcRequest()
, which will get URL
as an argument and used the fetch
method with await
keyword and defined call back function then()
and translate response into JSON data.
We have used the catch
method with console.log()
if any error occurs so that it will display the error in logs. Finally, we saved the URL and passed it to the funcRequest(url);
.
XML HTTP Request
It is an API in the form of an object which transfers data between a web browser and web server. XMLHttpRequest
is primarily used in AJAX (Asynchronous JavaScript and XML) programming.
It is not a programming language, but AJAX is a set of web development techniques that use several web technologies to develop asynchronous web applications on the client-side.
Basic syntax with GET
:
<script>
my_variable = new XMLHttpRequest(); // object
my_variable.onload = function() {
// Here, we can use the response Data
}
my_variable.open("GET", "MY_FILE_URL");
my_variable.send();
</script>
In the above JavaScript source, we have created the XMLHttpRequest
object, and then we defined the call-back function during the loading of a request. We have used the open
function, passed the request method type and URL as an argument, and called the send()
method of XMLHttpRequest()
.