Creating an ajax chart with Morris

Sometimes we need to display data in a visual way, for aesthetic reasons or readability ( not going into a long and boring data tables). Lately i used Morris Charts to display electricity consumption, and it is a very good library and verstile. In this tutorial i use it with an ajax call and make it all dynamic, let’s start.

We will start with the html code. it doesn’t matter what is your html, but that there will be an element with an id you can connect the cart to:

                        <!-- MULTILINE CHART -->
                            <div class="box box-success">
                                <div class="box-header text-center">
                                    <h3 id="main-chart-title" class="box-title"></h3>
                                </div>
                                <div class="box-body chart-responsive">
                                    <div class="chart" id="trendsmultiline" style="height: 300px;"></div>
                                </div><!-- /.box-body -->
                            </div><!-- /.box -->

 Here i used the id: trendsmultiline.

Now we can creat the ajax call. i cleaned the code to make it easier to understand. So there are no parameters, no validation and so on, we just make an ajax call to a php page that will return a hand coded array for creating the chart dynamically:

    $("#trendspicker").on('click', function (e) {
      e.preventDefault();
 
      $.ajax({
      type: "POST",
      dataType: 'json',
        url: "functions/gettrendsdata.php", 
        data: { 
        }, 
        beforeSend: function () {

        },
        complete: function () {
          
        }
    })
    .done(function (data) {
            
            var thekeys = Array();

            for (var r in data) {
              keys = Object.keys(data[r]);
              thekeys.push(keys);
            }

            var thefirst = thekeys[0].shift();
            var therest = thekeys[0];
            
            multiline1.options.xkey = thefirst;
            multiline1.options.ykeys = therest;
            multiline1.options.labels = therest;
            multiline1.setData(data);

            })
    .fail(function () {
              
                alert("error occured");
            });

 So basically we call a php page,on success we loop the results and assign the values from the results to what we need. this is the php page, it is a hard coded array. in the real world you would connect to a databse or do whatever is needed to get the data for the chart:

        $multilinevalues = array(
            array( 'quorter' => "2011 Q1" , 'elevator' => 3, 'load' => rand(2,10) , 'music' => 5 ) ,
            array( 'quorter' => "2011 Q2" , 'elevator' => 10, 'load' => 1, 'music' => 2) ,
            array( 'quorter' => "2011 Q3" , 'elevator' => rand(2,10) , 'load' => 4,'music' => 10 ) ,
            array( 'quorter' => "2011 Q4" , 'elevator' => 3 , 'load' => 3, 'music' => rand(2,10)) ,
        );
        
        echo json_encode($multilinevalues);

 once this data is returned ( in a json format here) we assign it with this code:

            var thekeys = Array();
            for (var r in data) {
              keys = Object.keys(data[r]);
              thekeys.push(keys);
            }

            var thefirst = thekeys[0].shift();
            var therest = thekeys[0];

            multiline1.options.xkey = thefirst;
            multiline1.options.ykeys = therest;
            multiline1.options.labels = therest;
            multiline1.setData(data);

 Notice that we loop the results and cut it to our needs. In this case we assing the xkeys,ykeys, the labels and the data. Like this this chart will be dynamic and we will not need to hard code anything else.

Now we connect all this to the chart itself, like so:

    var multiline1 = Morris.Area({
          element: 'trendsmultiline',
          behaveLikeLine: true,
          data: [], // Set initial data (ideally you would provide an array of default data)
          xkey: [],
          ykeys: [],
          labels: [],
          pointSize: 0
        });

 Again, notice that we made the xkeys, ykeys,labels and data to expect an array. and we already prepared these arrays with the loop.

This is it folks. Morris charts is very verstile and pleasent to the eyes. Obviously it have many more options. For these go through their API.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.