7

I want to update the chart drawn by jqPlot sequentially in time intervals.

My use case is such that the AJAX call returns only a single value. For e.g.:

1st AJAX call: 20
2nd AJAX call: 30
3rd AJAX call: 40
4th AJAX call: 32

So i want to make plot the graph like:

First: only 20
Second: 20,30
Third: 20,30,40
Fourth: 20,30,40,32

Can we extract already plotted data in JQPlot and then append this new data set and redraw the graph??

Can any one help please??

Sangram Mohite
  • 735
  • 4
  • 11
  • 23

2 Answers2

14

You will need to store the data in an array then push new data to the array within each ajax call.

Here is a simple demo using a button to start the AJAX updates on a 3 second interval:

/* store empty array or array of original data to plot on page load */

var storedData = [3, 7];

/* initialize plot*/

var plot1;
renderGraph();

$('button').click( function(){
    doUpdate();
    $(this).hide();
});

function renderGraph() {
    if (plot1) {
        plot1.destroy();
    }
    plot1 = $.jqplot('chart1', [storedData]);
}
/* sample data for demo*/   
var newData = [9, 1, 4, 6, 8, 2, 5];


function doUpdate() {
    if (newData.length) {
        /* used to pull new number from sample data for demo*/
        var val = newData.shift();

        $.post('/echo/html/', {
            html: val
        }, function(response) {
            var newVal = new Number(response); /* update storedData array*/
            storedData.push(newVal);
            renderGraph();               
            setTimeout(doUpdate, 3000)
        })

    } else {
        alert("All Done")
    }
}

DEMO: http://jsfiddle.net/ZqCXP/

charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • I'm using it with backbone.js in which I have to destroy the older view. Its working fine, but it doesn't look cool when the scrolling happens after re-plotting the graph with the updated data. Do you have any solutions for that? – Neha Choudhary Feb 27 '13 at 06:53
5

Let me add to @charlietfl answer. When you use replot() it takes 2 times longer to redraw, rather than with destroying jqplot. So use destroy() to redraw plot.

$.jqplot('chart1', [storedData]).replot();

http://jsfiddle.net/zjjvm/ it takes 46sec to draw running sine using replot()

plot1.destroy();
plot1 = $.jqplot('chart1', [storedData])

http://jsfiddle.net/p9SbP/ it takes 25sec to draw the same using destroy()

shukshin.ivan
  • 11,075
  • 4
  • 53
  • 69