Retrieving Data from a JSON URL and Publishing it on a Website

I have been experimenting with various coding methods, specifically p5js.org's, but I am facing difficulties in getting the json code to display on my website using document.write. Strangely, it does show up in the console log. Any suggestions?

var bibleVerse;

function setup() {
  loadJSON('http://labs.bible.org/api/?passage=votd&type=json', gotData, 'jsonp');
}

function gotData(data){
  println(data);
  bibleVerse = data;  
}    

document.write(bookname.chapter.verse.text);

Answer №1

Assuming that the p5js library functions properly, you should refrain from using document.write in your code. Instead, locate where you would like the data to appear on your webpage and insert it into that specific element using its unique id.

For instance, suppose you want to display a quote within a paragraph:

<p id="quote">Alternate Text</p>

To achieve this, replace any instances of document.write with the following snippet:

document.getElementById("quote").innerHTML = data;

Incorporating all these elements, your JavaScript code may resemble the following:

function setup() {
  loadJSON('http://labs.bible.org/api/?passage=votd&type=json', gotData, 'jsonp');
}

function gotData(data){
  document.getElementById("quote").innerHTML = data;
  // note: var bibleVerse is never used
}  

The text "Alternate Text" serves as a fallback in case the JavaScript functions encounter errors.


For those new to web development: if you opt not to utilize jQuery's $(document).ready() function, ensure that the JavaScript script is placed inside the <body> tag towards the bottom. This arrangement ensures that the page content loads first before executing the JavaScript code.

Answer №2

By following this code in a sequential manner:

var scriptureVerse;

function initialization() {
  loadJSON('http://labs.bible.org/api/?passage=votd&type=json', dataRetrieved, 'jsonp');
}

function dataRetrieved(data){
  console.log(data);
  scriptureVerse = data;  
}    

document.write(bookname.chapter.verse.text);

The code executes the following actions:

  1. Creates a variable called scriptureVerse
  2. Defines an initialization function
  3. Defines a dataRetrieved function
  4. Attempts to write bookname.chapter.verse.text to the document.

This setup will not be successful due to the following reasons:

  1. The initialization function is not being called anywhere in the code
  2. document.write is being executed prior to the dataRetrieved function
  3. The variable bookname has not been defined
  4. Regardless of the sequence, using document.write after page load completion is not recommended

To rectify this issue, consider the following steps:

  1. Include a placeholder in the HTML (e.g.,
    <div id="verse"></div>
    ) where the verse will be displayed
  2. Attach the initialization function to a DOM event (such as
    document.addEventListener('load', initialization);
    )
  3. Replace document.write with the following in the dataRetrieved function:

Example:

var textNode = document.createTextNode(data.bookname.chapter.verse.text);
document.querySelector('#verse').appendChild(textNode);

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

The Mean stack application is throwing an error message: "user.comparePassword is not

This section contains my user models in the file named "user.js". var mongoose = require('mongoose'); var bcrypt = require('bcryptjs'); let emailLengthChecker = (email) => { if (!email) { return false; } else { if (emai ...

Guide on converting a string into an array using PHP

My log file has a structure similar to the following: [{"ip":"XXX","prop1":"d","prop2":"xxx","prop3":{"index":0,"type":"xxx"},"id":"xxxxx","reason": "xxx [xxx]"}] [{"ip":"XXX","prop1":"d","prop2":"xxx","prop3":{"index":0,"type":"xxx"},"id":"xxxxx","reaso ...

Is it possible to control the positioning of a tooltip for an input element?

Currently, I am creating a filtering list that requires text input elements for each column due to limited space. Each input will initially display the name of the corresponding column and then clear when clicked by the user. To help users remember which ...

The issue with 'this' not resolving correctly within a prototype method is causing unexpected behavior in the context of inheritance

I've created a constructor that extends a module in node.js called (https://github.com/fluxxu/evalidator). Within this extended constructor, I've defined two additional methods in the prototype, with **method B** calling method A using the ' ...

Using JSON with Google Chart Tools

When referring to this example at , it is noted that the method data.addRows() requires a list of lists. A URI (/data/mydata.json) can be accessed to retrieve the following data: [["Canada", 66], ["Turkey", 10], ["Hungary", 23], ["Italy", 49]] Despite a ...

An unhandled error has occurred, please address

While developing a multiplayer survival game, I encountered an issue with nested message component collectors causing the innermost collector to fail. To resolve this, I implemented a promise that would be resolved once the outermost collector ends. Howeve ...

Displaying a list of entities in a dropdown menu upon loading an HTML page through a web API

I am currently working on loading all entities available in the CRM through the web API, and I have successfully retrieved all required information. URL/api/data/v8.0/EntityDefinitions?$select=SchemaName,LogicalName,IsValidForAdvancedFind&$filter=IsVa ...

Array JSON Encoding

I've been attempting to retrieve data from the database and store it in an array, then convert that array into a json string. However, when I try to display the results, nothing is being shown. Can anyone help me identify what might be causing this is ...

Performing synchronized execution in a node.js application by utilizing the 'readline' package

Struggling with the asynchronous nature of node.js, despite hours spent on callbacks and researching. I have a program that reads lines from a file using the readline module in node, passing data to async functions within the program. The goal is to proces ...

Unexpected error arises in Typescript despite code functioning properly

As part of a practice project where I'm focusing on using webpack, ES6, npm and Typescript implementation, I have successfully set up loaders for 'awesome-typescript-loader' and 'babel-loader', which are bundling the code properly. ...

Is there a method to determine if localForage/indexedDb is currently handling data operations?

Currently, I am working on a webapp that utilizes async localForage (specifically angular localForage). My goal is to alert users if they attempt to close the browser window while there are ongoing localForage operations. I have observed that some browser ...

The concept of encapsulation in JavaScript, which refers to the ability of

I'm currently developing a small app that involves using the jQuery ajax call to make SOAP calls to an external API. My goal is to create a "generic" function, but I'm encountering issues with variable scoping within the innermost function of the ...

JSON retrieved images are failing to appear in a grid layout

Hey there, I'm facing an issue with the layout of images on my website. I am fetching data from a JSON file to create a grid of images, but unfortunately, all the images are displaying in a single column instead of a grid. I am aiming for a 4 wide ima ...

An easy way to add an array to another array within a Redux reducer

Imagine having this condition in the reducer: case POST_LOAD_SUCCESS: return { ...state, posts: [...payload] } The payload for this action is an array [{post_1},{post_2},{post_3},{post4},{post5}]. When this acti ...

Issue with code displaying boxes according to selected radio checkboxes

I stumbled upon this Code Snippet, but for some reason, I can't seem to make it work on my website or even on a simple test page. I'm not sure what I'm overlooking? Check out the JS Fiddle: http://jsfiddle.net/technologrich/tT48f/4/ I&apos ...

Why does Axios keep timing out despite successful testing in Postman?

Trying to set up a single request for my app using axios with express/node js. Here is the code snippet that was generated through the Postman app. I have attempted different variations by creating my own form, but I always end up with the same result. co ...

Discovering the previously dropped value from a droppable div

Currently, I am developing a dynamic formula generator using jQuery's drag and drop functionality. Here is what I have accomplished so far: I have two lists: <ul id="head"> <li class="horizontal">Salary</li> <li class="h ...

Parsing additional JSON strings from a single file

Having two separate JSON files, I am looking to combine them and extract JSON strings from one of the files. {"ipAddress":"1.1.1.1","port":80, "protocol":"http"} {"ipAddress":"1.1.1.1", "domainName":"domain.com"} I attempted a solution, but it is not fu ...

Using JavaScript to parse a time string and update it by adding minutes

$.getJSON("api/times", function(times) { var time1 = times.departure; // 14:36:30 (string) var minutesToAdd = parseInt(times.minutesToAdd); // 6 var total = "?"; // How can I add minutesToAdd to time1? }); I need to manipulate the time1 variab ...

Updating JSON data from PHP using jQuery periodically

I currently have a PHP script that is running multiple queries, saving the results in a multidimensional associative array, and then encoding it as JSON. The structure of my JSON file looks like this: {"1":{"name":"Bob","score":18},"3":{"name":"Robert","s ...