0
<!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 ?

Ivar
  • 6,138
  • 12
  • 49
  • 61
Keshav
  • 39
  • 5
  • Looking at that URL, value is a property from the root of the object. It is not part of the category. So instead of `data.value` use `json.value`. – Ivar Mar 23 '21 at 15:16
  • 1
    @Ivar Thanks. **json.value** did the trick. – Keshav Mar 23 '21 at 15:19

1 Answers1

0
var data = json.value;
var message = '<h2>'+data+'</h2>';

Change these two lines like this, you will get the result.

In the API, categories is an empty array and the value is the keywoard that contains the joke data.