Learn four different ways to make API calls in JavaScript, including XMLHttpRequest, Fetch, Axios, and jQuery.
In this tutorial, We will show you how to make an API call in javascript. In JavaScript, it was really important to know how to make HTTP requests and retrieve the dynamic data from the server/database. JavaScript provides some built-in browser objects and some external open source libraries to interact with the APIs.
xmlHttp.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>XML http request</title>
<script>
let request = new XMLHttpRequest();
request.open("GET", "https://jsonplaceholder.typicode.com/users");
request.send();
request.onload = () => {
console.log(request);
if (request.status === 200) {
// by default the response comes in the string format, we need to parse the data into JSON
console.log(JSON.parse(request.response));
} else {
console.log(`error ${request.status} ${request.statusText}`);
}
};
</script>
</head>
<body></body>
</html>
fetch.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>XML http request</title>
<script>
async function getUsers() {
let response = await fetch(
"https://jsonplaceholder.typicode.com/users"
);
let data = await response.json();
return data;
}
getUsers().then(data => console.log(data));
</script>
</head>
<body></body>
</html>
axios.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Axios</title>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
axios
.get("https://jsonplaceholder.typicode.com/users")
.then(response => {
console.log(response.data);
})
.catch(error => console.error(error));
</script>
</head>
<body></body>
</html>
jquery-ajax.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Ajax Api call by jQuery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$.ajax({
url: "https://jsonplaceholder.typicode.com/users",
type: "GET",
success: function(result) {
console.log(result);
},
error: function(error) {
console.log(error);
}
});
});
</script>
</head>
<body></body>
</html>
Source Code: https://github.com/jayanthbabu123/all-possible-ways-making-api-call-javascript
Subscribe: https://www.youtube.com/channel/UCNVKOc0Ya-MVHElzxT7htxw
#js #javascript