Display JSON data into HTML with jQuery

Viewed 921

I wanted a simple way to display text and author into HTML like this:

text: You can observe a lot just by watching
author: Yogi Berra

Here, I tried to do it with jQuery and it's returning blank on the screen and undefined when logged out unless I removed text from (data.text).

$.ajax({
  url: "https://type.fit/api/quotes",
  method: "GET"
}).then(function(data) {
  $("#text").text(data.text);
  $("#author").text(data.author);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <p id="text"></p>
  <p id="author"></p>
</div>

What am I missing here?

3 Answers

The data is in JSON format, so it needs to be parsed. It is also an array, so the 2nd element needs to be selected to display the chosen text:

$.ajax({
  url: "https://type.fit/api/quotes",
  method: "GET"
}).then(function(data) {
  data = JSON.parse(data);
  
  $("#text").text(data[1].text);
  $("#author").text(data[1].author);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <p id="text"></p>
  <p id="author"></p>
</div>

  1. Data is retuning in string form, in order to make it JSON, you need to parse data
  2. The data is array of object so you cannot access it by using data.text until you use loop or manually pick the index you want to display.

$.ajax({
  url: "https://type.fit/api/quotes",
  method: "GET"
}).then(function(data) {
  data = JSON.parse(data);            // Added this code
  $("#text").text(data[0].text);      // Updated
  $("#author").text(data[0].author);  // Updated
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <p id="text"></p>
  <p id="author"></p>
</div>

Bonus: If you want to display all the data from the JSON, printing it in a single element with ID is not the best way to do it, use loop and dynamic DOM creation

If you do a console.log(data) inside your .then, you will see the data is coming as a stringified JSON.

So before using Data, you have to JSON.parse(data) your data back into JSON itself.

const parsedData = JSON.parse(data);

Then you will run into another problem, as the data does not contain a single Element. It's an array. So either select a specific element from it, or loop over it.

$.ajax({
  url: "https://type.fit/api/quotes",
  method: "GET"
}).then(function(data) {
  const parsedData = JSON.parse(data);
 
  console.log(parsedData);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Related