How to make jQuery AJAX update chart

In the last chapter we show you how to make Flot realtime update chart, and we will continue to show you how to make AJAX update chart in this chapter.

System load chart(AJAX)

We use the example from last chapter,in here we only show you the part that we have modified,if you want to see the complete instructions of making a update chart,you can always go back to the last chapter.

Preparing data

First,we have to create three arrays call cpu、cpuCore and disk,then we create initial data by calling initData().
 
    
        var cpu = [], cpuCore = [], disk = [];
        var dataset;
        var totalPoints = 100;
        var updateInterval = 1000;
        var now = new Date().getTime();

        function initData() {
            for (var i = 0; i < totalPoints; i++) {
                var temp = [now += updateInterval, 0];

                cpu.push(temp);
                cpuCore.push(temp);
                disk.push(temp);
            }
        }
        

Create update function

We create a function call update(), this function needs to be passed into a parameter call "_data",this is used for retrieving the data we get from backend.In the beginning of the function,we remove the first itme of array,then we insert the data from backend into array,and we change the value for label attribute with the last retrieved data,this makes the value in the legend changed along with each update.In the end,we call $.plot again to redraw the chart.
    
        var temp;

        function update(_data) {
            //remove first item of array
            cpu.shift();
            cpuCore.shift();
            disk.shift();

            now += updateInterval

            //add the data retrieve from backend to array
            temp = [now, _data.cpu];
            cpu.push(temp);

            temp = [now, _data.core];
            cpuCore.push(temp);

            temp = [now, _data.disk];
            disk.push(temp);

            //update legend label so users can see the latest value in the legend
            dataset = [
                { label: "CPU:" + _data.cpu + "%", data: cpu, lines: { fill: true, lineWidth: 1.2 }, color: "#00FF00" },
                { label: "Disk:" + _data.disk + "KB", data: disk, color: "#0044FF", bars: { show: true }, yaxis: 2 },
                { label: "CPU Core:" + _data.core + "%", data: cpuCore, lines: { lineWidth: 1.2}, color: "#FF0000" }       
            ];

            //redraw the chart
            $.plot($("#flot-placeholder1"), dataset, options);

            //prepare for next update
            setTimeout(GetData, updateInterval);
        }
        
This is the data object we retrieved from backend script.
    
        {"cpu":47, "core":11, "disk":550}
        
We use jQuery.ajax() to get the data from backend script.
    
        function GetData() {
            //set no cache
            $.ajaxSetup({ cache: false });

            $.ajax({
                url: "http://static.jqueryflottutorial.com/AjaxUpdateChart.aspx",
                dataType: 'json',
                success: update,  //if success, call update()
                error: function () {
                    //if fail, prepare next update
                    setTimeout(GetData, updateInterval);
                }
            });
        }
        

Backend script

Because we are unable to get the real CPU loading data from server,so we use random values to simulate,and output it as JSON format.

C# backend script(AjaxUpdateChart.aspx)
    
        protected void Page_Load(object sender, EventArgs e)
        {
            Page.Controls.Clear();
            Random rnd = new Random();

            int CPUloading = rnd.Next(0, 100);
            int CPUcore = CPUloading - 30 < 0 ? 0 : rnd.Next(0, CPUloading - 30);
            int Disk = rnd.Next(56, 1024);

            Response.Write("{\"cpu\":" + CPUloading + ", \"core\":" + CPUcore + ", \"disk\":" + Disk + "}");
        }
        

Practice

You can find the source code of this example and test it online! Go to Example Tester