Is there a way to change the class and content of a div element without refreshing the page when the JSON data updates?

I have a JSON database that is updated frequently, and based on this data, I update the content of my webpage. Currently, I am using the following script to reload:

var previous = null;
var current = null;
setInterval(function() {
    $.getJSON("sampledatabase.json", function(json) {
        current = JSON.stringify(json);
        if (previous && current && previous != current) {
            console.log('refresh');
            location.reload();
        }
        previous = current;
    });
}, 1200);

The issue is that this script is meant for monitoring on a large screen in fullscreen mode, so the page blink during reloading is quite distracting.

During the refresh process (triggered by updating the database), I change the class of certain divs and display additional data from the database in them. Here's a snippet of the code:

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
        var i;
        var output = document.getElementsByClassName("env");
        var myObj = JSON.parse(this.responseText);
        for (i = 0; i < output.length; i++) {
            if (myObj.instances[i].status == "UP") {
                output[i].classList.add("passed")
            } else 
              output[i].classList.add("notPassed")
  
          output[i].innerHTML = "<span class=\"originalsize\">" + myObj.instances[i].id + "</span><br>" + myObj.instances[i].time
        }
    }
};
xmlhttp.open("GET", "sampledatabase.json", true);
xmlhttp.send();

Is there a way to update only the divs without causing the unpleasant blink when the page reloads?

Answer №1

If you're looking to make asynchronous calls in jQuery, the $.ajax() method is a handy tool, as detailed on W3 Schools.

Take a look at this interactive example on JSFiddle

Within that JSFiddle demo, I've used the $.each() method to parse JSON data and dynamically insert it into div elements.

function FetchPosts() {
  $.ajax({
    dataType: "json",
    url: "https://jsonplaceholder.typicode.com/posts",
    success: function(data) {
      //console.log(data);
      $.each(data, function(index, item) {
        console.log(item);
        $('.container').append('<div class="posts"><div id="post_container"><h3 id="post_title">' + item.title + '</h3><hr><div id="post_body">' + item.body + '</div><hr><span id="post_userid">' + item.id + '</span></div></div>');
      });
    }
  });
}

You can even utilize the setInterval() method for automated refreshing.

Here's an illustration of how to set it up:

let interval;
let time = 5000; // 5 seconds

function initiateRefresh() {
    interval = setInterval(FetchPosts(), time);
}

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

Decompressing data in JavaScript using Zlib

I am attempting to unpack zlib-compressed XML data as shown in the following link: https://drive.google.com/file/d/0B52P0MZLTdw8ZzQwQzVpZGZVZWc Using online decompression services, such as: , works fine In PHP, I have successfully used this code to get t ...

How can I display a clicked-on div while hiding all other divs using jQuery?

I want to create a website where a button can show and hide a specific div, but my challenge is; How can I ensure that clicking on one button hides all other divs? Here is the JavaScript code: function showHide(divId){ var theDiv = document.getEleme ...

Modify the color of the background for a flex-wrap list

I am facing a situation where I have a list with an unknown number of items, but I need to control the height of its container. To achieve this, I am using flex-flow: wrap column to split the list. The list starts off hidden and is displayed using jQuery&a ...

Angular Bootstrap Popover will now automatically hide after a short period of time due to the removal of the tt_isOpen variable in ui-bootstrap-tpls-0

I recently attempted to implement the ingenious directive created by runTarm for managing angular-bootstrap-popover-hide-after-few-seconds. While using ui-bootstrap 0.11.0.js presented no issues, transitioning to ui-bootstrap-0.12.0 proved problematic as ...

The ajax function threw an error because it couldn't determine the length of an undefined property

When attempting to retrieve the number of objects within an array, I encountered an error stating 'length' of undefined. Here is my JavaScript code: .. success: function(data){ console.log(data.item.length); }, This is my P ...

importing with a specific name may result in errors, while importing everything with * from does not

Exploring the directory layout of features within my react application: feature1 actions actionTypes.js crud.js component.js container.js reducer.js sagas.js sagas.test.js services.js index.js feature2 ...

Display the scrollbar in a Boostrap CSS table when the content exceeds the height of the div

I've been working on a Bootstrap page that looks like this: https://i.sstatic.net/kpHMM.png On the right side, there are two tables inside a div. The issue I'm facing is that when the tables contain too many elements, they grow in height instea ...

Automatically resizing a multi-part CSS background based on content dimensions

My current CSS project has hit a snag that I can't seem to solve: There is a box on the left side of the site that contains three images - a top image, an optional and stretched middle image, and a bottom image. I want this left box to automatically ...

The data type 'string' cannot be assigned to the data type 'Position'

Currently, I am in the process of converting React js to typescript. The component being used is a Class Component. I would like to obtain CSS settings through props and apply them to an element. How can I resolve this issue? render(){return( <span st ...

If you want to retrieve the calculated value of a div using jQuery

I have a scenario where I have 3 list items (li) under an unordered list (ul). I am interested in finding the height of these list items, but without explicitly defining their height. So far, when inspecting with Firebug, I noticed that the computed height ...

How to ensure uniform button sizes in an HTML form by setting them all equal to the size

The code snippet provided below demonstrates a basic form with two submit buttons. <form> <input type="submit" value="< Previous"> <input type="submit" value="Next >"> </form> Depending on the value attribute, the bu ...

How can I update select options using JavaScript in Symfony 2.0?

I've spent countless hours searching online, but to my surprise, I couldn't find any discussions on this specific topic. Here is the Form I'm working with: class propertyType extends AbstractType { public function buildForm(FormBuilde ...

Retrieving updated information from database (PHP)

I'm currently working on a piece of code that pulls data from my database. However, I'd like this data to automatically 'refresh' every 5 seconds so that any new entries meeting specific criteria will appear without needing to refresh t ...

What is the most effective method for tracking file upload progress using SSE?

I am currently working on creating a file upload progress feature that is compatible with older browsers using AJAX. In HTML5, there is the xhr.upload.progress event which works well for modern browsers, but I need an alternative for non-XHR2 browsers. I h ...

Troubleshooting Vue Single File Components Displaying Missing Styles

I'm currently attempting to incorporate styles into a vuejs single file component. I've successfully achieved this in a node app previously, but now I am working with a python/flask backend (not that it should make a difference). The Vue componen ...

Tips for utilizing the <br> element within a Bootstrap card?

Is there a way to break the line after "Other online payment" without affecting the card content alignment in bootstrap? Adding the <br> tag is causing issues with the alignment. Any thoughts on why this is happening? Thank you :) .user-ads { fo ...

Guide to Capturing a Comprehensive Stack Trace Using Winston 3

Here is how I have configured my logging system: const customFormat = printf(info => { return `${info.timestamp}: ${info.level}: ${info.message}: ${info.err}`; }); const newLogger = winston.createLogger({ level: "info", format: combine( ...

Overlap with upper picture formatting

I've been struggling to create an ion-card with two images: a main picture and a small book cover. Any ideas on how to achieve this? Note: The layout should have 2 images, one at the top and another as a small book cover. Check out this sample on St ...

Exploring Nested Divs with Vue Test Utils

Recently, I came across this shallowMounted vue component: <div class="card p-relative"> <div class="card-header"> <div class="card-title h4"> a lovely title <!----> <!----> </div> </div ...

Mandatory selection of jQuery extension

Currently, I am developing a custom jQuery plugin with the following code structure: (function($) { $.fn.foo = function(options) { var opt = $.extend({}, $.fn.foo.defaults, options); return this.each(function() { //code i ...