Attempt to retrieve JSON-formatted data from a repository on Git

As a novice, I am delving into the world of ajax and experimenting with json files. Utilizing JSON formatted data is something I am keen on mastering. However, my request seems to be yielding an empty outcome. An Update: Below is the piece of code I am working with:

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);
}

The issue persists as no data is getting returned. Why might this be?

Answer №1

To get the desired result, you must call the send() function and then patiently 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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to iterate through a JSON array for comparisons using Python?

Is there a way to compare two sets of JSON arrays in order to identify the additional elements present in File 2 that are not in File 1? See the example below: File 1: { "Cars": [{ "type": "Ford" }, { "type": ...

"Unexpected Results: Using the .each method in jQuery to print a JSON object displays more outcomes

An error has been detected in the code snippet below. The rJSON object consists of one sURL and one iURL when checked using console.log. However, after the each condition, the imgList displays 3 identical sURL and iURLs. Can you identify any issues with ...

Modifying an onClick handler function within a react element located in a node module, which points to a function in a prop declared in the main Component file

I have successfully implemented the coreui CDataTable to display a table. return ( <CDataTable items={data} fields={fields} ... /> ) Everything is working smoothly, but I wanted to add an extra button in the header of the C ...

Discovering a specific JSON object member by its corresponding string value

Let's consider a JSON file with information about books stored in it: { "store": { "book": [ { "category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", "price": 8.95 }, { "category": "fiction", "autho ...

Double clicking on a row value in a Bootstrap table

Struggling to retrieve the row value after a double click in a bootstrap table. Unfortunately, every attempt returns 'undefined'. Snippet of my code: $('#table').on('dbl-click-row.bs.table', function(field, value, row, $el) ...

The null error occurs when rendering with React's state array

When I try to call an API that emits JSON, I am encountering an issue. I call the promise API function in componentDidMount, set the state, and then call it in the render method, but it always returns a null error. I need assistance, please. Interface fo ...

Issue with jQuery's .height() method not updating

Here is the code I am working with: $(function() { $('#team-ch').click(function() { $('#team-camb-hert').height('auto'); }); }); I am trying to change the height of a div when a link is clicked. After adding an alert ...

jQuery is not defined when importing reactjs, bootstrap, and npm modules

Having trouble using Bootstrap in my React app, as I keep getting an error message saying Error: Bootstrap's JavaScript requires jQuery. I've already imported jQuery and tried various solutions found in other posts like: import $ from 'jque ...

Streaming large files with Node.js can lead to significant memory consumption and potential memory errors like OOM

My current project involves using node.js to download large files (300MB) from a server and then piping the response to a file write stream. While I have a good understanding of how pipes work in Node.js, I am encountering an issue where the memory usage o ...

In Lua, we can print the heart symbol ( ♡ ) after successfully parsing a JSON data

Here is the function I have created, utilizing lua-cjson which claims full UTF-8 support. function getPersonaName(sid64) local cjson = require "cjson" local r = http.request("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=###&ste ...

My element is not being animated by Elementbyclass

Without Using JQUERY The animation I'm trying to create isn't functioning properly. I attempted to utilize document.getElementsByClassName, but it's not working as expected. There are no errors, but the element is not animating correctly. ...

Compiling Directives in AngularJS for Faster Page Loading

I'm currently experiencing performance issues in my Angular application. The root cause seems to be the excessive use of a directive on a single page. Unfortunately, I don't have the time to break down this page into multiple sections. I am seek ...

The 'mergeMap' property is not found on the 'Observable<any>' type

Currently, I'm working on an HttpInterceptor within my Ionic 4 application. My goal is to retrieve the Bearer Authorization token stored in local storage. Although I attempted to utilize mergeMap for this task, I kept encountering the following error ...

Primefaces: Leveraging RequestContext for One-time Ajax Updates

I am facing an issue with updating a component on my view from my bean. The update only works once. When I press the second button, nothing happens even though the bean method in the action listener is being called. I have checked the browser log using F ...

Anticipating the completion of multiple observable subscription functions

Is there a way to replace and convert all words in an array using an object's method that returns an observable? I found a helpful solution on this post which uses bind to pass the correct value. After all subscriptions are complete, I want to execut ...

Angular2 - HTML not displaying the response

I am currently mastering angularjs2. In my latest project, I attempted to fetch data from an API and received a response successfully. However, I encountered an issue where the response is not rendering in homepage.component.html as expected. I am unsure o ...

`How can I incorporate personalized animations on Google Map V3 Markers as they are individually dropped on the map?`

This is a basic example of dropping markers one by one on Google Maps V3. I have implemented the drop animation when adding markers to the map. However, I am interested in customizing the drop with a fade animation. Is it possible using JavaScript or any ...

Implementing clickable actions to add new entries in a React.js application (using Redux toolkit)

I am currently working on my PET project using Redux toolkit and encountering some issues with inputs. When I add an input on click, it gets added correctly, but I am unsure if it is being added in the right place (it should be added in the ITEMS array). A ...

Unable to send email through Ajax/PHP contact form

It's quite amusing that it worked perfectly for one evening. After reaching out to my host, they assured me that there should be no issues with it not working. I even tried testing it in Firebug, but it appeared to be sending successfully. Additionall ...

Could using 'require' in node.js lead to a memory leak issue?

I have been working on a program that experiences continuous heap growth. The program is quite simple - it repeatedly tries to load an external file (SyntaxError) using require. However, this external module fails to load due to a syntax error present in i ...