Search code examples
javascriptajaxangularjspartial-page-refresh

JavaScript: Timer to refresh content of elements with same class


There is a web app I am designing. I'm using AngularJS on the front-end with a Java back-end. The web app is being deployed in a war file to a local JBoss server. I currently have a Java class that performs a series of calculations and sends that data as JSON to the client every 10 seconds. This works, but I want to update the elements that contain this data with AJAX(?).

In Angular I have a few $resource services that consume the Java RESTful API. This is all JSON data, which is the being propagated into the view by a single controller. I then have some HTML elements generated by ng-repeat that all have the same classes. I wanted to use one of these classes to trigger a refresh on all of the elements every 10 seconds. Here is a snippet with the ng-repeat I am talking about:

<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 snippet, the data that's being updated is mq.currentDepth.

And this is the code I am using to refresh:

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

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

I get a warning that basically states the way I am implementing AJAX will break my user interface, which it does after a series of 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 questions

  1. Can you update the contents of an element with a class in AJAX, or does that only work with IDs?
  2. Should I be using AJAX to refresh the page?
  3. If not, then how would I implement that with Angular?

Solution

  • Doing synchronous network calls from javascirpt will block the main thread, which may block your UI and hence is not adviced. To answer your questions.

    1. When you are using angular, you shouldn't access the elements using class or ids (using selectors), the way we use to do with jQuery. Instead you should use data-binding.
    2. You do not need AJAX to refresh the page.
    3. You can use your existing $resources for retrieving data. Once you have the data in controller, save that in a scope variable. Then you can use the same variables in your HTML using angular-expression to update the data.

      $scope.mqDepth = MqDepth.get({ id: id });