Search code examples
javascriptphpjsoncodeignitermorris.js

Unable to display Morris.JS Chart on Codeigniter page using JSON Data as input for Charts


I am using the latest Codeigniter and MorrisJS. I have created a View for the Charts and passing dynamic data through JSON, but that does not seem to work. I have made sure that all the dependent JS and CSS for MorrisJS is mapped on the View. When I give dummy data statically into the Chart options, it generates the chart perfectly. Only does not work when the JSON data is passed. Please could you guide me on this, I am sure I have made a silly mistake, but am not able to figure it out.

My View:

<div id="myfirstchart" style="height: 250px;"></div>
    <script>
        Morris.Bar({
            element: 'myfirstchart',
            data: <?php echo $graphData; ?>,
            xkey: 'MonthName',
            ykeys: ['totalTicket'],
            labels: ['Value']
        });
    </script>

My Controller:

    public function index(){
        $x['graphData']=json_encode($result);
        $this->load->view('common/header');
        $this->load->view('common/main_top_navbar');
        $this->load->view('reports/trends');
        $this->load->view('common/footer',$x);
    }

My Model:

class Reports_model extends CI_Model{
    function display_monthOnMonth_records(){
        $this->db->select('MONTHNAME(CreatedOn) as MonthName, count(TicketID) as totalTicket');
        $this->db->from('TBL_tickets');
        $this->db->group_by('MonthName');
        $this->db->order_by('
            FIELD(
                MonthName,
                "January",
                "February",
                "March",
                "April",
                "May",
                "June",
                "July",
                "August",
                "September",
                "October",
                "November",
                "December"
            )
            ');
        $query=$this->db->get();
        return $query->result();
    }
}

When I run this, I see on the Chrome Browser/page Inspect(F12), that data is showing for the data input, but it is not creating the Chart on Page.

From the Browser Inspect Result:

<script>

        Morris.Bar({
            element: 'myfirstchart',
            data: {"data":[{"MonthName":"January","totalTicket":"2500"},{"MonthName":"February","totalTicket":"2200"},{"MonthName":"March","totalTicket":"2350"}]},
            xkey: 'MonthName',
            ykeys: ['totalTicket'],
            labels: ['Value']
        });

</script>

Solution

  • Within the index() method, change :

        $x['graphData']=json_encode($result);
    

    into :

        $x['graphData']=json_encode($result->data);
    

    From what I see from the output, you have extra data parent.