Welcome Guest, Not a member yet? Register   Sign In
Passing Json Data From Controller To View For Morris.js Bar Chart
#1

I am using morris.js bar chart I am a bit confused on how to pass json data to it from my controller function.

My xkey is the days and user data is the count.


Code:
{"xkey":[[0,0],[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10],[11,11],[12,12],[13,13],[14,14],[15,15],[16,16],[17,17],[18,18],[19,19],[20,20],[21,21],[22,22],[23,23]],"user":{"data":[[2,"1"],[3,"1"]]}}


Question how can I get the json data from controller to the view for xkey and ykeys"user data".

My controller function


PHP Code:
public function chart_data() {
    $json = array();

    $json['xkey'] = array();

    $json['user']['data'] = array();

    $uri_segment $this->uri->segment(5);

    if (isset($uri_segment)) {
        $range $uri_segment;
    } else {
        $range 'month';
    }

    switch ($range) {
        case "week":
            $results $this->getUserTotalByWeek();

               foreach ($results as $key => $value) {
                $json['user']['data'][] = array($key$value['total']);
            }

            for ($i 0$i 24$i++) {
                $json['xkey'][] = array($i$i);
            }
                
            
break;

            default:
                echo "Your favorite color is neither red, nor green!";
    }

    $this->output->set_header('Content-Type: application/json; charset=utf-8');
    $this->output->set_output(json_encode($json));



On my view script


Code:
<script type="text/javascript">
$( document ).ready(function() {
    $('#range').on('click', function(e) {
        e.preventDefault();
        $.ajax({
            type: 'get',
            url: "<?php echo base_url('admin/dashboard/chart/chart_data');?>/" + $( "#range" ).val(),
            dataType: 'json',
            success: function(json) {
            if (typeof Morris != 'undefined') {
                Morris.Bar({
                    element: 'bar-example',
                    resize: true,
                    stacked: false,
                    xLabelAngle: 50,
                    grid: true,
                    gridTextSize: 10,
                    data: [
                    {m: '3', a: 1}, // need to pass $json['xkey'] and $json['user']"ykeys"
                    ],
                    xkey: 'm',
                    ykeys: ['a'],
                    labels: ['Users']
                });
            }
            }
        });
    });    
});
</script>
There's only one rule - please don't tell anyone to go and read the manual.  Sometimes the manual just SUCKS!
Reply
#2

Read This
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply




Theme © iAndrew 2016 - Forum software by © MyBB