Implementing a JavaScript timer to automatically update the contents of elements that share the same class

As I work on designing a web application, I am utilizing AngularJS for the front-end and Java for the back-end. The app is deployed in a war file on a local JBoss server. Currently, a Java class performs calculations and sends data as JSON to the client every 10 seconds. While this setup works, I am looking to incorporate AJAX to update the elements displaying this data.

Within Angular, I have several $resource services consuming a Java RESTful API. The JSON data is then rendered in the view through a single controller. Using ng-repeat, multiple HTML elements with the same classes are created. I aim to use one of these classes to trigger a refresh on all elements periodically. Here's a snippet showcasing the ng-repeat usage:

<div ng-repeat="mq in mqDepth">
     <progressbar class="mq" max="max" value="dynamic" ng-init="dynamic=mq.currentDepth" type="info>
        <span>
            {{dynamic}} / {{max}}
        </span>
     </progressbar>
</div>

In the above code snippet, the data being updated is referenced by mq.currentDepth.

The following code is utilized for refreshing:

function refreshQueue() {
    $('.mq').load('', function() {
        $(this).unwrap();
    });
}

refreshQueue();
setInterval(function() {
    refreshQueue();
}, 10000);

A warning indicates that my current AJAX implementation could potentially harm user experience by breaking the interface after repeated updates.

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/.

I have a few queries:

  1. Can you use AJAX to update elements with classes, or does it only apply to IDs?
  2. Is it advisable to utilize AJAX for page refreshes?
  3. If not, what would be the appropriate approach within Angular?

Answer №1

Executing synchronous network requests in JavaScript can cause the main thread to be blocked, potentially impacting the user interface. It is generally not recommended to do so. Here are some suggestions:

  1. When working with Angular, it is advised not to manipulate elements directly using class or IDs like you would with jQuery. Instead, utilize data-binding for a more efficient approach.
  2. There is no need to rely on AJAX calls to refresh a page.
  3. You can leverage existing $resources in Angular to fetch data. Store the retrieved data in a scope variable within the controller and then update your HTML content using angular-expressions.

    $scope.userData = UserData.get({ id: id });

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 click event fails to trigger on the <object> element

Within an anchor tag, there is an <object> element with an Angular click event attached to it like so: <a (click)="myAction()"> <object data="/images/icon.svg"></object> </a> Strangely, when clicking directly on the <ob ...

Passport JS receiving negative request

I'm currently experiencing an issue with the passport req.login function. When a user logs in using their email and password, instead of redirecting to /productos2 as intended, it routes to a bad request page. I am utilizing ejs and mongoose for this ...

Tips for integrating a fully revamped design for social network share buttons

Is it possible to customize social network like buttons similar to the ones shown in the attached image? ...

What is the process for setting up a "Highlight tab" feature in Next.Js?

I am currently working on implementing a selected tab feature in Next.Js. Users will have the ability to search for either Users or Posts by clicking on corresponding buttons. https://i.sstatic.net/mRBgQ.png Once the user clicks on a button, it should ch ...

Kindly attach the npm-debug.log file along with your support inquiry

When I try to use the "watch" command, I encounter the following error: "Please include the following file with any support request: C:\wamp\www\chandco\wp-content\themes\chandco\npm-debug.log". Below are the files in q ...

Switching sub components based on routing through navigation links after logging in

I'm having an issue with my routing setup while transitioning from the login page to the main page. Here's how my Routes are structured: App.jsx <BrowserRouter> <Routes> <Route path="/main/" element={<Main ...

Python: Stay Up-to-Date with Google App Engine Live Updates

Is it feasible to develop an application using Google App Engine and Python to create a basic calculator that can perform calculations without requiring the page to refresh? Specifically, I am interested in knowing if there is a way for users to input a f ...

Submitting a Django form seamlessly without reloading the page

Currently using Django-Angular, I am attempting to submit a form and access the data on the backend. Despite achieving this, I have noticed that the page reloads when saving the form. Is there a way to achieve this without having the page render? forms.py ...

Utilizing the 'Day' Function in Visual Basic to alter the date and submit a form according to the day of the week

I have been developing a Windows application that utilizes the WebBrowser control to automate form filling based on specific criteria. One challenge I encountered is with dates on certain forms, where different rules apply depending on the day of the week. ...

Can Vue.js be paired with pure Node.js as a backend without relying on Express?

After successfully building a project with both vue js and node js, specifically with express, I'm curious if it's feasible to solely utilize node js without frameworks like express. ...

Exploring mysterious traits through inheritance

In my Angular and TypeScript project, I have defined an interface: export interface A { name: string; } Now I have two other interfaces that inherit from interface A: export interface B extends A { year: number; } export interface C extends A { ...

Having trouble with the Ionic loader? The $ionicLoading.show() function doesn't seem to be working on the first try

I've encountered a strange issue with the $ionicLoading directive where I'm attempting to display a loader on every state change. .run(['$rootScope','$ionicLoading', function ($rootScope, $ionicLoading){ $rootScope.$on(&apo ...

Tips for making a background image responsive using ng-style in AngularJS

Can anyone assist me in fixing the gap space issue in a responsive view with an attached jpg background image? Follow this link for more details: enter image description here ...

The reason for the lack of proper response after submitting a request to the server with the parameter (ID) in a REST API using NODEJS and EXPRESSJS

There is a Node module called dishRouter.js that serves as the Express router for the REST API endpoint /dishes/:dishId. index.js const express = require('express'); const http = require('http'); const morgan = require('morgan&ap ...

Setting up GameClosure on a Windows machine

Is it possible to install GameClosure on Windows? The installation guide mentions that only OSX is officially supported, but there have been reports of success running it on Linux and Windows. However, the process for doing this is not well-documented. A ...

The ajax request is unable to retrieve the JSON data from the specified URL

Hello, I am looking to retrieve some data using AJAX and JSON. The JSON data can be found at the following URL: Below is my PHP code: $sql = "SELECT * FROM kasir"; $hasil = mysqli_query($mysqli, $sql); $results = array(); foreach($hasil as $row){ ...

Issues rendering ThreeJS geometry data imported from Json file

Having been a dedicated user of this website for some time now, I must admit that this is the first instance where I find myself in need of posting a question. The issue at hand revolves around a Json file from which I extract data and manipulate it with m ...

Angular - Highlight a section of a string variable

Is there a way to apply bold formatting to part of a string assigned to a variable? I attempted the following: boldTxt = 'bold' message = 'this text should be ' + this.boldTxt.toUpperCase().bold() ; However, the HTML output is: thi ...

ways to validate the calling function in jquery

One of the challenges I'm facing is identifying which function is calling a specific error function that is used in multiple places within my code. Is there a method or technique to help determine this? ...

Tips for making dropdowns stay visible in Vue.js with Tailwind CSS

Looking to create a dropdown menu using Vue.js and Tailwind CSS. Currently, when hovering over the "Genres" link, the dropdown appears but disappears as soon as the mouse moves away. Is there a way to keep it visible as long as the mouse is over the dropdo ...