Being able to automatically update my JSON file without needing to manually refresh the webpage is a feature I am interested in exploring

I have a server that automatically updates a JSON file. However, the JavaScript code I have implemented below reads the JSON file and displays it to the client, but it always refreshes the page.

I am looking for a solution on how to read my JSON file every time it gets updated without having to refresh the webpage.

After searching online, it appears that I may need to use AJAX to achieve this. However, I couldn't find much information beyond that. Do I need to make any updates to my JSON file itself?

Below is the snippet of index.html code that I am currently using to fetch data from archive.json:

<script>

fetch('archive.json')
    .then(function (response) {
        return response.json();
    })
    .then(function (data) {
        appendData(data);
    })
    .catch(function (err) {
        console.log('error: ' + err);
    });

function appendData(data) {
    console.log(data.velas.length);
    var mainContainer = document.getElementById("myData");
    for (var i = 0; i < data.velas.length; i++) {
        var div = document.createElement("div");
        div.innerHTML = 'Tempo: ' + data.velas[i].tempo;
        mainContainer.appendChild(div);
    }
}

</script>

Any assistance or guidance would be greatly appreciated!

Answer №1

Give this code a shot, I've provided detailed explanations in the comments

<script>

const UPDATE_INTERVAL = 5; // Updates every 5 seconds
var mainContainer = document.getElementById("myData");

async function displayData() {
    // Make the API request
    const response = await fetch('archive.json');
    const data = await response.json();    

    // Check if there is valid data received
    if(data == undefined && data == null) return
    
    // Update the DOM
    var mainContainer = document.getElementById("myData");
    mainContainer.innerHTML = '' // Clear the existing content of the main container
    for (var i = 0; i < data.velas.length; i++) {
        var div = document.createElement("div");
        div.innerHTML = 'Time: ' + data.velas[i].tempo;
        mainContainer.appendChild(div);
    }
}

setInterval(() => { // Make an API call every 5 seconds (UPDATE_INTERVAL) <- You can adjust this value here
   displayData()
}, UPDATE_INTERVAL * 1000)

</script>

Answer №2

Hopefully, I have grasped your query correctly.

document.querySelector('button').addEventListener('click',()=>{
   var xhttp = new XMLHttpRequest();

xhttp.onreadystatechange = function () {
  if (this.readyState == 4 && this.status == 200) {
  document.querySelector('.get').innerHTML=`${JSON.parse(this.responseText).ip}`
  };
}
xhttp.open("GET", "https://ipapi.co/json/", true);
xhttp.send();


})
<button>Get</button>
<div class="get">
</div>

Answer №3

My error was not due to JSON or AJAX codes, but simply because I was running it on a local server causing it to refresh regardless.

However, Adilson's solution with a timer perfectly met my needs:

Appreciate the assistance everyone!

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

Ways to swap out element within ViewContainerRef in Angular

I am currently expanding my knowledge of Angular and I have encountered a challenge regarding dynamically creating components and swapping them within a single container. Here is the setup: <ng-container #container></ng-container> Here are the ...

Toggle between images in Vue.js when an image is clicked

Hey there, I'm pretty new to Vue and could use some assistance with implementing a certain logic. I have a JSON file that contains information about polaroids I've taken, such as their IDs, names, image names, and descriptions. Here's a sni ...

An error occurred during the extraction of nested JSON data in a SQL query

I have encountered an issue while running an SQL query to extract nested JSON data. SELECT watsonResponse.responseId, watsonResponse.chatId, d.* FROM watson_response_table watsonResponse CROSS JOIN LATERAL ( SELECT d2.* FROM ...

The issue with the jQuery click event arises when utilizing the "Module Pattern"

Exploring the Module Pattern as described by Chris Coyyer here, I, an intermediate front-end JS developer, have encountered a problem. Specifically, when attempting to utilize a jQuery selector stored in the settings object, I am unable to trigger a click ...

JavaScript code to find all possible subarrays of an array containing n elements

I've been working on creating a function that can generate subsets from an array based on a specified number of elements, but I haven't quite cracked it yet. I came across a function that was supposed to do the job, but it turned out to be too c ...

The webservice encountered an issue while trying to interpret the JSON Request coming from a PHP file

I'm working on integrating a webservice into my PHP document. While I've successfully used this webservice with an android app, I am encountering issues when trying to access it through PHP. When I test the webservice using Chrome's advanced ...

Is the runTest.ts class in the vscode-test setup ever utilized in the project? Its purpose remains unclear even in the example project

Being a novice to Typescript, JavaScript, and VScode Extensions I have set up a vscode-test following the guidelines provided here: https://code.visualstudio.com/api/working-with-extensions/testing-extension#custom-setup-with-vscodetest Based on the hel ...

Validation in Laravel appears to be ineffective when managing schedules

I have a table that contains schedules for each subject. I want to ensure that every schedule is unique and not duplicated. The table includes columns for room, teacher, time, day, and checker who verifies the schedule. It's essential that there are n ...

What are some methods to improve the performance of this jQuery-powered webpage?

I've developed a contact script that leverages jQuery for ajax requests and animations. However, the sluggish aspect arises when using a hashchange plugin to improve the functionality of the back button. Upon completing the animation for the 'f ...

Exploring the capabilities of the Google Books API

I'm having difficulty utilizing the Google Books API My experience with JSON is limited. Here is my form: <form action="action.php" method="POST"> <div class="form-group"> <div class="campos"> <label> Se ...

What is the best way to include a form within every row of an HTML datatables structure?

I have a regular table that is populated with data fetched via Ajax, and it appears like this: Ajax <script> $(document).ready(function() { $('#mytable').DataTable( { "ajax": "myurl", "dataType": 'json', ...

Is there a way to align two canvases perfectly on top of each other?

My current challenge involves the need to position one HTML5 canvas on top of another. So far, I have successfully accomplished this using the following method: <canvas id="lower" width="900" height="550" style="position: absolute; left: 0; top: 0; z-i ...

Avoid nesting ternary expressions when possible - consider alternative solutions

I am currently working on a React component that has 4 different states: advisoryResults, results, noResults, and newAccount. While I initially thought about using a ternary expression for this, it turns out that it is not allowed in this case. Can you su ...

Minimize redundancy in the process of adding functions to a function queue

Currently, I am delving into JavaScript animations and utilizing multiple functions to add components to the animation queue. The structure of these functions is quite repetitive as shown below: function foo(arg1, arg2) { _eventQueue.push(function() { ...

What is the best method to consistently convert a deeply nested object into a tabular format that can be easily reversed

Imagine having a deeply nested object with an unknown structure until runtime, like: { "row-0" : { "rec-0" : { "date" : 20220121, "tags" : [ "val-0" ] }, ...

Utilize jQuery's .append() function to dynamically insert content into your webpage

I currently have tab elements set up like this: <div class="tab-pane fade active in" id="tab-a"> </div> To populate the content of that tab with a JavaScript string array, I am using the following code snippet: var full_list = ""; for (var ...

Access array information using AngularJS

Sorry for any language issues. I am trying to figure out how to extract an array data from AngularJS in order to save it using Node.js. This is my AngularJS script: angular.module('myAddList', []) .controller('myAddListController&apos ...

Chrome console displaying error: "API request open method is not a function."

Check out my weather app on Code Pen Here's the code for my weather app (apologies if it's overwhelming): var button=document.getElementById('submit'); var zipcode; var lat; var lng; var weather; var iconId; var temp; // Function t ...

Exploring the world of web scraping using NodeJS and cheerIO

Can anyone help me figure out why I can't retrieve the HTML content while web scraping with Node.js and Cheerio? When I use the .html() function, it's showing an error saying that it is not a function. Here is the code snippet where I'm try ...

Translating a few lines of JavaScript into C#

I'm looking to convert some code from JavaScript to C#, but I'm having trouble grasping a certain section... function getHisto(pixels) { var histosize = 1 << (3 * sigbits), histo = new Array(histosize), inde ...