Waivio

Recommended Posts

Random Jokes Using AJAX.

0 comments

here-to-share106.933 years agoHive.Blog

Recently I have implemented a simple beginner level project where you will get random jokes according to the number you put. I used Ajax in this project.

Let me jump to the codes.


HTML codes of "index.html" file

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" integrity="sha512-EZLkOqwILORob+p0BXZc+Vm3RgJBOe1Iq/0fiI7r/wJgzOFZMlsqTa29UEl6v6U6gsV4uIpsNZoV32YZqrCRCQ==" crossorigin="anonymous" />

    <title>Jokes</title>
  </head>
  <body>
    <div class="container" style="padding:25px">
      <h3 style="text-align:center">Feeling bored ? Get some random jokes using AJAX !!!</h3><br>
          <input type="number" id="numberJokes" value="1" required>
          <button type="button" name="button" id="get-data">Get Jokes!</button>
          <p id="output"></p>
    </div>
&nbsp;

    <script src="script.js"></script>
  </body>
</html>




JS codes of "script.js" file

document.getElementById('get-data').addEventListener('click', loadJokes);
&nbsp;
function loadJokes (){
  let number = document.getElementById('numberJokes').value;

  let xhr = new XMLHttpRequest();

  xhr.open('GET', `https://api.icndb.com/jokes/random/${number}`, true);

  xhr.onprogress = function(){
    document.getElementById('output').innerHTML = '<h3>Loading.......</h3>';
  }

  xhr.onload = function(){
    if (this.status === 200){
      let data = JSON.parse(this.responseText);
      let jokes = data.value;
      let output = '<ol>';

      jokes.forEach(function(item){
        output += `<li>${item.joke}</li>`;
      });

      output += '</ol>';
      document.getElementById('output').innerHTML = output;
    }
  }
  xhr.send()
}


Output


https://images.hive.blog/DQmPZbLD9CnTwJumZJKUTb3Ytb7FUgMNP3A17fje6H5CLkW/image.png

  • You will get the number of jokes according to the number you provided. I have used "Chuck Norris" API here.

Thank You

Comments

Sort byBest
AI
Waivio AI Assistant
How can I help you today?