Random Jokes Using AJAX.

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>



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




JS codes of "script.js" file

document.getElementById('get-data').addEventListener('click', loadJokes);


function loadJokes (){
  let number = document.getElementById('numberJokes').value;

  let xhr = new XMLHttpRequest();

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

  xhr.onprogress = function(){
    document.getElementById('output').innerHTML = '

Loading.......

'
; } xhr.onload = function(){ if (this.status === 200){ let data = JSON.parse(this.responseText); let jokes = data.value; let output = '
    '; jokes.forEach(function(item){ output += `
  1. ${item.joke}
  2. `
    ; }); output += ''; document.getElementById('output').innerHTML = output; } } xhr.send() }

    Output


    image.png

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

    Thank You

H2
H3
H4
3 columns
2 columns
1 column
Join the conversation now
Logo
Center