-1

Context: I created Flask API to server up jokes, and was creating relatively static frontend for it. I wanted a joke from there API to be on the front end and callable but a button click using a JQuery Ajax Call

Issue: I have read all the documentation on iterating over JQuery JSON objects - The Using Stringify method, and I cannot get the response object to display the joke, I just keep getting [OBJECT OBJECT]

Code Thus Far:

place_joke = () => {
  var settings = {
    url: "http://localhost:6969/insult",
    method: "GET",
    timeout: 0
  };

  const joke = document.getElementById("joke");
  joke.innerText = $.ajax(settings).done(function (response) {
    const joke_resp = JSON.stringify(response);
    console.log(joke_resp);
    return joke_resp;
  });
};

What am I doing wrong? This may be a mediocre question, just frontend JS is not a language I work with often.

Point of Clarification: I see the calls and the resp codes of 200 on my API's server, So I know the calls are happening and getting responses from my API

The API Returns:

{
    "Yo Mama So...": "Yo mama so hairy people think she’s an Ewok."
}
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – user3840170 Jan 03 '23 at 15:40
  • I don’t see any iteration in here either, so the question title is terrible. – user3840170 Jan 03 '23 at 15:42

1 Answers1

2

You did not read the part where $.ajax does not return the result.

jQuery AJAX has a callback and that is where you want to show the result

For example

(assuming { "Yo Mama So...": "Yo mama so hairy people think she’s an Ewok."})

const place_joke = () => {
  $.getJSON("http://localhost:6969/insult", response => {
    $("#joke").text(
      Object.values(response)[0]
    ); 
  });
};
mplungjan
  • 169,008
  • 28
  • 173
  • 236