Sam
Sam

Reputation: 157

How can i pass a JSON array from php to JS?

im trying to populate a morris.js chart from a set of results. In my controller I create an array of the results and use json_encode to create a json array, here is the output in my view using print_r:

{"Positive":7,"Negative":26,"Pending":786,"Contact the Clinic":242,"Misc":2} 

How would I pass this to my morris.js chart to populate the chart using this data as label / value pairs? everything I try I get either a blank chart or an "undefined" variable or "NaN". Here is my controller:

function execute_search()
{
    // Retrieve the posted search term.
    $search_term = $this->input->post('search');

    // Get results count and pass it as json:
    $data = $this->search_model->count_res('$p_results_data');
    $pos = 0; $neg= 0; $pen = 0; $cont = 0; $misc = 0;
    foreach ($data as $item) {
        if ($item['result'] === 'Positive') {
            $pos++;
        } elseif ($item['result'] === 'Negative') {
            $neg++;
        } elseif ($item['result'] === 'Pending') {
            $pen++;
        } elseif ($item['result'] === 'Contact the Clinic') {
            $cont++;
        } else {
            $misc++;
        }
    }
    $res = array("Positive"=>$pos, "Negative"=>$neg, "Pending"=>$pen, "Contact the Clinic"=>$cont, "Misc"=>$misc);
    $data = json_encode($res);

    // Use the model to retrieve results:
    $this->data['results'] = $this->search_model->get_results($search_term);
    $this->data['chart'] = $data;
    $this->data['totals'] = $this->search_model->total_res('$total_res');

    // Pass the results to the view.
    $this->data['subview'] = ('user/search_results');
    $this->load->view('_layout_admin', $this->data);
}

and my morris.js:

$results = "<?php echo $chart ?>";
new Morris.Donut({
    element: 'donutEg',
    data: [
        $results
    ],
});

Any help is greatly appreciated

Upvotes: 0

Views: 438

Answers (2)

Brian Gottier
Brian Gottier

Reputation: 4582

In javascript, JSON.parse is your friend, assuming you have JSON that was created by PHP's json_encode function:

$results = "<?php echo $chart ?>";
new Morris.Donut({
    element: 'donutEg',
    data: [
        JSON.parse( $results )
    ],
});

OR POSSIBLY

$results = "<?php echo $chart ?>";
new Morris.Donut({
    element: 'donutEg',
    data: JSON.parse( $results )
});

BUT THE WAY I DO IT

In the view:

<input type="hidden" id="chartData" value='<?php echo $chart; ?>' />

In the JS (using jQuery):

var chartData = $('#chartData').val();
new Morris.Donut({
    element: 'donutEg',
    data: JSON.parse( chartData )
});

After looking at the documentation for morris.js, I found that this is how you can do it the right way:

// Looking at the docs for morris.js:
// http://jsbin.com/ukaxod/144/embed?js,output

// This is your data, but it's all in one json object
var chartData = JSON.parse( $('#chartData').val() );

// We need to break up that object into parts of the donut
var donutParts = [];
$.each( chartData, function(k,v){
    donutParts.push({
        label: k,
        value: v
    });
});

// Now create the donut
Morris.Donut({
    element: 'donutEg',
    data: donutParts
});

Upvotes: 1

jeroen
jeroen

Reputation: 91742

Assuming that your morris.js is a normal javascript file, you cannot use php there by default: The server will not parse the .js file so the php source code will appear in your javascript.

You need to either:

  • Put the morris.js script contents in a php page in a javascript block so that the php gets parsed;
  • Make an ajax request from your morris.js script to get the data from the server in a separate request;
  • Set up your server to parse .js files as if they are / contain php.

The last one is just to illustrate what you would need, I would not recommend doing that.

Upvotes: 2

Related Questions