<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>AJAX</title>
</head>
<body>
<h1>Learn AJAX</h1>
<div id="output"></div>
<button id="trigger">Get a Joke</button>
<script type="text/javascript">
var joker = document.querySelector('#trigger');
joker.addEventListener('click',function(){
loadJoke();
});
function loadJoke(){
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function(){
if(this.readyState == 4){
if(this.status == 200){
var json = JSON.parse(ajax.responseText);
var data = json.categories[0];
var message = '<h2>'+data.value+'</h2>';
output.innerHTML=message;
console.log(json);
}
}
}
ajax.open('GET','https://api.chucknorris.io/jokes/random',true)
ajax.send();
}
</script>
</body>
</html>
I'm new to AJAX and working on the above code. I'm trying to print the field value of the array categories. But I always get this error
text.html:28 Uncaught TypeError: Cannot read property 'value' of undefined at XMLHttpRequest.ajax.onreadystatechange
Any suggestions where am I going wrong ?