<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ajax call</title>
</head>
<body>
<h1> Ajax call </h1>
<button type="button" id="nextbtn" >Send ajax </button>
<button type="button" id ="popbtn" class="btn btn-secondary btn-sm">Fetch data </button>
<div class = "container">
<h1>Employee list </h1>
<ul id="list">
</ul>
</div>
</body>
<script>
var pophandeler = document.getElementById("popbtn");
console.log(pophandeler);
pophandeler.addEventListener('click', pophandelers)
function pophandelers()
{
console.log("Fetch data button clicked")
const xhr = new XMLHttpRequest(); // instantiate an XHR object
xhr.open('GET' , 'https://dummy.restapiexample.com/api/v1/employees', true); // open the object(request type, fetch data from ?, synch/asynch (non blocking : agay ki cheez chalti rahay aur background mein request chalti rahay )) Get: only url
xhr.getResponseHeader('Content-type', 'application/json' )
// allow
xhr.onprogress = function(){ // If you want to add any loader or spinner
console.log('On progress'); // Until and unless onload is called, on progress will run
}
xhr.onreadystatechange = function (){
console.log("readystate is" , xhr.readyState);
}
xhr.onload = function () { // it means you are on the 4th state of xhr statechange
if(this.status === 200){
let obj = JSON.parse(this.responseText)
console.log(obj);
let list = document.getElementById('list')
str = "";
for(key in obj)
{
str += `<li>${obj[key]} </li>`;
}
list.innerHTML = str;
}
else{
console.log("File not found")
}
}
xhr.send();
console.log("We are done")
}
</script>
</html>