Understanding the data flow when fetching chart data using AJAX

đź‘Ť:1

You don’t have to use jQuery. This JavaScript library contains a number of functions to simplify making AJAX calls and accessing the DOM, though some would argue that the convergence of browser APIs make it less necessary these days. Nevertheless, it remains popular.

Your first task is probably to fire off an AJAX operation upon page load. You can start off by adding this JavaScript directly to the page, though you’ll probably want to add it as a minified asset once you have your logic working.

function ajax() {
    // @todo Add your ajax logic in here
}

// Load the AJAX data into the chart as soon as the DOM is ready
$(document).on('ready', function() {
    ajax();
});

It is common to do read operations using a get operation returning JSON, for which getJSON would work fine. Add this logic in place of the @todo comment above.

After that, you’ll probably want to do a periodic refresh of your data, say every 60 seconds. You can do this thus:

setInterval(60 * 1000, ajax);

Note the interval timer works on milliseconds, hence the need to multiply by 1000.

One downside of the above is that if you expect a large number of users, or wish to reduce the interval to a very small value, your web server will be processing a lot of redundant requests (since most calls will result in no screen change). Using AJAX here is therefore not very scalable.

A better approach is to configure the server to push updates to browsers using Web Sockets. However, this requires a separate kind of web server, and so I probably would not recommend it for you just yet.

Leave a comment