Search code examples
htmljqueryajaxget

Storing GET method returned data into variable


The below code fetches text from an URL (Which is readable in debug console), But I am having trouble accessing that data as a variable that I can then use elsewhere.

The code currently produces "data is not iterable" errors and I have tried JSON.parse(ing) the data without much success.

If I for example wanted to print the fetched data onto the body of the page, How would I go about doing that?

$(document).ready(function() {
  $("#ajaxButton").click(function() {
    $.get("https://v2.jokeapi.dev/joke/Programming?type=single", function(data, status) {
      console.log(data);

      var addStr = "";
      for (var x of data) {
        addStr += "<p>" + x.Any + "</p>";
      }

      $("#here").html(addStr);
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div id="here"></div>
<p id="joke">Want to hear a joke?</p>
<br>
<button id="ajaxButton">yes</button>


Solution

  • The issue is because the deserialised response isn't an array, it's an object. This is why you can't iterate it in your for loop.

    To do what you require simply output the content of the joke property in the response to the UI:

    jQuery($ => {
      const $here = $('#here');
    
      $("#ajaxButton").on('click', function() {
        $.get("https://v2.jokeapi.dev/joke/Programming?type=single", response => {
          $here.html(`<p>${response.joke}</p>`);
        });
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <p id="joke">Want to hear a joke?</p>
    <div id="here"></div>
    <button id="ajaxButton">yes</button>