jow3ew0l
jow3ew0l

Reputation: 45

How do I get JSON data to show up in HTML div?

Trying to get this json data to show up in HTML div

[{
  "botten": ["Krispig", "tunn"]
},
]  

The div in the HTML document has the class name box1_data. This is my script:

var bottenInfo = document.getElementsByClassName("box1_data");

$.getJSON('choosepizza.json', function(choosePizzaData) {
  choosePizza(choosePizzaData);

  function choosePizza(choosePizzaData) {
    var request = new XMLHttpRequest();
    request.open('GET', 'choosepizza.json');
    request.onload = function() {
      var data = JSON.parse(request.responseText);
      renderHTML(data);
    };
    request.send();

    function renderHTML(bottenData) {
      var text = "";
      for (var i = 0; i < bottenData.length; i++) {
        text += '<p>' + bottenData[i].botten + '<p>';
      }
      bottenInfo.innerHTML = text;
    }
  });

What am I doing wrong?

krispig and tunn is supposed to show up in the .box1_data div.

Upvotes: 0

Views: 559

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337656

Your code seems rather confused regards to the difference between plain JS and jQuery and also how AJAX works. You're currently making the same request twice using different logic, parsing an object that's already been parsed, not correctly accessing the resulting object, and are attempting to access a node collection as a single element.

To fix this you simply need to loop through the result, which will be deserialised to an object for you automatically, and generate the HTML to be placed in the required element:

$.getJSON('choosepizza.json', function(choosePizzaData) {
  var html = choosePizzaData[0].botten.map(function(botten) {
    return '<p>' + botten + '</p>';
  });
  $(".box1_data").html(html);
});

This is a working example without the AJAX which obviously won't work here on SO:

// the response from the request:
var choosePizzaData = [{
  "botten": ["Krispig", "tunn"]
}]

// within the AJAX callback
var html = choosePizzaData[0].botten.map(function(botten) {
  return '<p>' + botten + '</p>';
});
$(".box1_data").html(html);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box1_data"></div>

Upvotes: 4

Related Questions