Dalek
Dalek

Reputation: 4318

Try to extract a json formatted data from a git repository

I am a beginner, trying to learn ajax and working with json files. I would like to use of JSON formatted data. But the result of my request is an empty text. Update: Here is my piece of code:

var quoteContainer=document.getElementById("random-quote");
var btn=document.getElementById("btn");
btn.addEventListener("click",function(){
   var myRequest=new XMLHttpRequest();

   myRequest.open("GET","https://raw.githubusercontent.com/4skinSkywalker/Database-Quotes-JSON/master/quotes.json",true);
   myRequest.addEventListener('load', function () {
       var myData=JSON.parse(myRequest.responseText);
       console.log(myRequest.responseText);
       renderHTML(myData);  
   });
   myRequest.send();
});


function renderHTML(data){
    var LenJson=data.length;
    var Num=Math.random()*LenJson;
    console.log(Num);
    var QuoteString="<p id='quote-text'>"+data[i].quoteText+"</p>"
    var AuthorString="<p id='quote-author'>"+data[i].quoteAuthor+"</p>"
    quoteContainer.insertAdjacentHTML('beforeend',QuoteString);
    quoteContainer.insertAdjacentHTML('beforeend',AuthorString);
}

It still doesn't return any data. Why?

Upvotes: 0

Views: 207

Answers (2)

Patrick Roberts
Patrick Roberts

Reputation: 51957

You need to send() it and wait for it to load:

var quoteContainer = document.getElementById("random-quote");
var btn = document.getElementById("btn");

btn.addEventListener("click", function() {
  var myRequest = new XMLHttpRequest();

  myRequest.open("GET", "https://raw.githubusercontent.com/4skinSkywalker/Database-Quotes-JSON/master/quotes.json", true);
  
  myRequest.addEventListener('load', function() {
    var myData = JSON.parse(myRequest.responseText);

    renderHTML(myData);
  });
  
  myRequest.send();
});

function renderHTML(data) {
  var LenJson = data.length;
  var Num = Math.floor(Math.random() * LenJson);
  
  var QuoteString = "<p id='quote-text'>" + data[Num].quoteText + "</p>";
  var AuthorString = "<p id='quote-author'>" + data[Num].quoteAuthor + "</p>";
  
  quoteContainer.insertAdjacentHTML('beforeend', QuoteString);
  quoteContainer.insertAdjacentHTML('beforeend', AuthorString);
}
<button id="btn" type="button">Generate Random Quote</button>
<div id="random-quote"></div>

Upvotes: 1

Ben Schroeder
Ben Schroeder

Reputation: 356

You forgot to include myRequest.send(), which you should have on the line after you run the open() method.

More information: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

Upvotes: 1

Related Questions