Mohammed Asker
Mohammed Asker

Reputation: 71

Display JSON data into HTML with jQuery

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?

Upvotes: 2

Views: 2972

Answers (3)

Mugentoki
Mugentoki

Reputation: 1616

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>

Upvotes: 1

Abhishek Pandey
Abhishek Pandey

Reputation: 13558

  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

Upvotes: 1

sbgib
sbgib

Reputation: 5828

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>

Upvotes: 4

Related Questions