Question

I'm using codeigniter and I need to populate a graph with a multidimensional array from PHP.

I use two functions to get the data. Those are the functions that returns the arrays, where "get_num_instalaciones_mes" and "get_num_bajas" returns a number (int)

function ajax_instalaciones_3meses() {
    $fecha['mes'] = date('m');
    $fecha['anio'] = date('Y');
    $output['num_instalaciones_actual'] = get_num_instalaciones_mes($fecha['mes'], $fecha['anio']);
    $fecha = $this->v3_operaciones_model->mes_anterior($mes, $anio);
    $output['num_instalaciones_1menos'] = get_num_instalaciones_mes($fecha['mes'], $fecha['anio']);
    $fecha = $this->v3_operaciones_model->mes_anterior($mes, $anio);
    $output['num_instalaciones_2menos'] = get_num_instalaciones_mes($fecha['mes'], $fecha['anio']);
    echo json_encode($output);
}

function ajax_bajas_3meses() {
    $fecha['mes'] = date('m');
    $fecha['anio'] = date('Y');
    $output['num_bajas_actual'] = get_num_bajas_mes($fecha['mes'], $fecha['anio']);
    $fecha = $this->v3_operaciones_model->mes_anterior($mes, $anio);
    $output['num_bajas_1menos'] = get_num_bajas_mes($fecha['mes'], $fecha['anio']);
    $fecha = $this->v3_operaciones_model->mes_anterior($mes, $anio);
    $output['num_bajas_2menos'] = get_num_bajas_mes($fecha['mes'], $fecha['anio']);
    echo json_encode($output);
}

and this is the code that populates the chart in the view, where 'data' is the array I have to populate with both functions (y: instalaciones, z: bajas)

new Morris.Bar({
        element: 'graf_instalaciones_bajas',
        data: [
            {x: 'AGO-2013', y: 20, z: 5},
            {x: 'SEP-2013', y: 40, z: 5},
            {x: 'OCT-2013', y: 33, z: 10},
            {x: 'NOV-2013', y: 24, z: 1},
            {x: 'DIC-2013', y: 44, z: 10},
            {x: 'ENE-2014', y: 31, z: 5}
        ],
        barColors: ['#00FF00', '#FF0000'],
        xkey: 'x',
        ykeys: ['y', 'z'],
        labels: ['Instalaciones', 'Bajas']
    }).on('click', function(i, row){
    console.log(i, row);
    });
Was it helpful?

Solution

I use JSON to get data from PHP output (on some other page) and then populate the data in Morris with the JSON object.

Rough example:

var array = [];

function myData() {
    $.getJSON('data_source_link', function(data) {
        array = data;
        console.log(JSON.stringify(array)); // to ensure the data is actually captured
    }
    return array;
}

var myChart = Morris.Line({
    element: 'graph',
    xkey: 'your_x_key',
    ykeys: 'your_y_keys',
    labels: ['Your Labels'],
    ...
});

setInterval(function() {
    myChart.setData(myData());
}, 1000);

Hope this helps. :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top