Casper Boon
Casper Boon

Reputation: 57

Read JSON and implement it in HTML

First of all, sorry for my bad English, isn't the best ;)

So I'm new to working with JavaScript, Ajax and, jQuery. Since a young age I've been interested in coding. A friend of mine wants an update on their website I made for them a little while ago. They have a small podcast/radio station.

What I'm trying to do is make an automatic link between the podcasts they post on MixCloud and their website. I followed some tutorials and grave throw the forms on this website, but I can't get the script to work properly and get the information out of the JSON file that MixCloud makes with their API.

This is what I've got so far. I can't figure out what I'm doing wrong since I'm very very new to this. I tried different methods, but this is the closest I've got.

const Http = new XMLHttpRequest();
const url = 'https://api.mixcloud.com/itmotr-radio/cloudcasts/';
Http.open("GET", url);
Http.send();
Http.onreadystatechange = (e) => {
  console.log(Http.responseText)
}

function append_json(XMLHttpRequest) {

  //Set Up the template
  var s = $("#postTemplate")[0].innerHTML.trim();
  var holder = document.createElement('div');
  holder.innerHTML = s;
  var template = holder.childNodes;

  var episode = document.getElementById('episodes');
  Object.keys(XMLHttpRequest).forEach(function(object) {

    //Clone Template
    var newEpisode = $(template).clone();

    //Populate it
    $(newEpisode).find(".data.name").html(object.episodetitle);

    var img = $(newItem).find(".data.pictures.320wx320h")
    $(img).attr("src", object.coverimg)

    //Append it
    $(".episodes").append(newEpisode);

  });
}

$("document").ready(function() {
  append_json(XMLHttpRequest);
});
.episodes {
  background: white;
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(auto-fit, minmax(320px, 380px));
  grid-auto-rows: 370px;
  grid-auto-flow: dense;
  justify-content: center;
  padding-top: 10px;
}

.episode {
  background: rgb(255, 255, 255);
  border: 1px solid grey;
  text-align: center;
}

.episodetitle {
  font-size: 20px;
  color: red
}

.coverimg {
  width: 320px;
  max-height: 320px
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

<div class="episodes">

  <script type="text/template" id="postTemplate">

    <div class="episode">

      <img class="coverimg" src="">
      <p class="episodetitle"></p>

    </div>

  </script>

</div>

For some reason, I can't get the data out of the JSON file and it won't show in the HTML. I built this script with a lot of help from this article: Populate grid <div> & <p> with JSON data file

Can someone help me out and get it working with me? The JSON file that needs to be read is: https://api.mixcloud.com/itmotr-radio/cloudcasts/

Upvotes: 0

Views: 129

Answers (2)

Tobin
Tobin

Reputation: 2018

There's a few things going on so I will address each individually, and you can put them together as the learning :) Your general structure is OK though, nice going so far!

jquery

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">/script>

this is an old version, use

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

AJAX

const Http = new XMLHttpRequest();
const url='https://api.mixcloud.com/itmotr-radio/cloudcasts/';
Http.open("GET", url);
Http.send();
Http.onreadystatechange=(e)=>{
console.log(Http.responseText)
}

This is all taken care of within jquery automatically. Have a read of the AJAX documentation. This is a good example to learn with, it's quite simple (lots of defaults you can use).

$.ajax({
  url:'https://api.mixcloud.com/itmotr-radio/cloudcasts/',
  success:function(data){
    //Do stuff with the data here (as JSON, it should be auto parsed into an object)

    //for example (psuedo code..)
    for(var i = 0; i < data.length;i++){
      //Use the data variable passed in with the success function.
      createNewElement(data[i]) // do something with each object in the array (see below)

    }
})

Create new element

 var newEpisode = $(template).clone();

 //Populate it
 $(newItem).find(".data.name").html(object.episodetitle);

 var img = $(newItem).find(".data.pictures.320wx320h")
 $(img).attr("src", object.coverimg)

 //Append it
 $(".episodes").append(newEpisode);

As you have jquery already we can use a lot of the functions easily. The element to append we can build in jquery, or just use a string in javascript containing your HTML. As you are adding in dynamic data, it makes sense to make the elements.

createNewElement(datum){
 // This function creates a new element each time it is called and appends it to the 
 let $para = $('<p></p>') // make new <p> element
  .addClass('episodetitle') // add the class property and actual classes
  .text(thing.episodetitle) // set the text content of the element
//we have created "<p class='episodetitle'>This is the Title</p>"

//Alernatively we can do it all in one go
let $img = $('<img class="coverimg" src="'+datum.imagesource+'"/>') 

// Now we create the container div for these 2 elements
let $newEpisode = $('<div></div>').addClass('episode')

$newEpisode.append($para) // Add the para into our div
  .append($img) // append the image element into the div


$(".episodes").append($newEpisode); // append the div to the coagulate div

}

Upvotes: 1

Casper Boon
Casper Boon

Reputation: 57

@Tobin

So now I edited my script to this:

            $.ajax({
            url:'https://api.mixcloud.com/itmotr-radio/cloudcasts/',
            success:function(data){
            //Do stuff with the data here (as JSON, it should be auto parsed into an object)
            var newEpisode = $(template).clone();

            //Populate it
            $(newItem).find(".data.name").html(object.episodetitle);

            var img = $(newItem).find(".data.pictures.320wx320h")
            $(img).attr("src", object.coverimg)
                
            let $para = $('<p></p>').addClass('episodetitle').text(thing.episodetitle)

            let $newEpisode = $('<div></div>').addClass('episode')
            $newEpisode.append($para)
                

     // GETTING A ERROR :28 Uncaught SyntaxError: Identifier '$para' has already been declared. When trying to do the same for the coverimg.

            let $para = $('<p></p>').addClass('coverimg').text(thing.coverimg)
          
            let $newEpisode = $('<div></div>').addClass('coverimg')
            $newEpisode.append($para)

            //Append it
            $(".episodes").append(newEpisode);
            
            }
            })

But now de second $para gives me an error because it's already declared...

But I made one change in the first script, changed a 'newItem' to 'newEpisode' and now it renders my layout, but none of the information in the JSON file is loaded in. And it makes 5 items, while there are supposed to be 2 'files' in the JSON file. What goes wrong here?

Upvotes: 0

Related Questions