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 there a way to extract individual values from a for-each loop in JavaScript?

Would appreciate any guidance on my use of Bootstrap vue table with contentful's API. I'm currently working on implementing a for loop to iterate through an array and retrieve the property values. Although the console.info(episodes); call success ...

How to rotate a SVG transformation matrix around its center point

CSS .square { background-color: green; height: 40px; width: 40px; } JS var square = { sizeReal : { "width": 40, "height": 40 } , position : { "x": 100, "y": 100 } }; $(". ...

What purpose does sending null to XMLHttpRequest.send serve?

Have you ever wondered why send is often called like this? xhr.send(null) instead of just xhr.send() ? W3, MDN, and MSDN all mention that the argument is optional. Additionally, the ActiveX control seems to work without it: hr=pIXMLHTTPRequest.Create ...

Avoid duplicate submissions while still enforcing mandatory fields

Let's start with a basic form that only asks for an email address: <form action="NextPage.php" method="post"> <input type="email" name="contact[email]" required id="frmEmailA" autocomplete="email"> <button type="submit">Subm ...

I wish to adjust the font size as well as resize the table elements simultaneously

Adjusting the height and width of the table should automatically adjust the font size as well. <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>jQuery UI Resizable - Default functiona ...

Tips for serializing and deserializing a property with a dynamic property name based on the data

I am currently facing a challenge with deserializing the following JSON object using Newtonsoft Json Serializer. The issue lies with the variable named "2010-12" as it represents a specific month and will change to "2010-01" in the next iteration due to dy ...

Generating a three-level unordered list using arrays and for-loops in JavaScript/JSON

Are there more efficient ways to achieve the desired results from this JSON data? Can someone assist me in understanding why it is working and if it can be optimized for cleanliness? <div id="accordion" class="display-data"> ...

Checking if a JSON key contains a particular value in Wiremock

Looking at the request URL provided below: http://localhost:9082/v1/action/query I also have a set of requests defined in a wiremock request file: {"queryString":"Select firstname, lastname, workphone, id, accountId from mydetails} { &qu ...

Avoiding cheating in a JavaScript game

I am in the process of creating a JavaScript/JQuery game that resembles a classic brick breaker. The game includes features such as scoring, levels, and more. I have plans to add a leaderboard where users can submit their final scores. However, my concer ...

What is the process for obtaining intersection set data from an array?

I'm trying to find the intersection set within an array only containing type 1 and 2. Can you help me with that? var arr = [ { id: 1, auths: [ { authId: 1, type: 1, value: 'Test1' }, { authId: 2, type: 1, ...

Unable to scroll after the webpage redirects

I am currently working on developing a website for uploading images with a comment feature. The comments section is displayed below the image in the 'imagedisplay.php' file. If a user is not logged in, they are redirected to the sign-up page and ...

Clicking on Rows in DataTables: Enhancing

I have been utilizing the jquery datatables plugin, and have encountered an issue with the row click functionality. Strangely, it only seems to work on the first page of the table. When I navigate to any subsequent pages, the row click fails to respond whe ...

The NPM command fails to execute the Webpack script, yet it successfully runs when manually entered into the terminal

Working on my project with Electron-React-Boilerplate, I encountered an issue while running npm run build-renderer. Despite the script appearing to finish, I receive an error. If I manually enter the code related to the build-renderer script in the termin ...

Jackson is losing type associations while converting an abstract type to a specific type

My issue is similar to the problem discussed in "Jackson and generic type reference", but with an additional complexity - my abstract generic class needs to be mapped to a concrete type. This functionality was working perfectly fine with Jackson v2.5.3, bu ...

The CSS transition duration is not being applied properly on the initial transition effect

Looking to create a dynamic set of sliding divs that can be triggered with the press of a button. Each div will contain a thumbnail image and accompanying text. The goal is to enable the user to navigate through the content by clicking the left or right bu ...

Encountering a problem with utilizing the equalTo() method in Firebase Realtime Database in a React

I'm having trouble randomizing and querying a specific node in my database based on the ShopNo When I use equalTo, I can't seem to retrieve the desired node. Instead, I'm only getting a randomized value based on the total number of Shop ent ...

Is it possible to create a collapse and expand animation that does not involve transitioning the `height

After extensively researching, I have come across numerous articles advocating for the use of transform and opacity for achieving smooth CSS transitions. An example can be found here: The prevailing notion always revolves around: ...the optimization ...

Creating numerous strings using template literals

I am looking to create multiple strings using a template literal and an array variable. For instance, a template literal allows you to replace an expression with its content in a string: var = "world"; tpl = `Hello ${var}!`; console.log(tpl); // Hello wor ...

Is it possible to retrieve and display an object from an API using its unique ID?

I created a straightforward application. The main page displays a list of movies fetched using an API, and upon clicking on a particular movie, it leads to a new page with detailed information about that movie. On the details page, another API call is ma ...

Using Angular to retrieve JSON data from a static file

Currently, I am attempting to implement this AngularJS example from a tutorial on Login Tutorial Example. Instead of storing the username and password as simple strings, I am trying to retrieve them from a local file. I understand that this may not be the ...