javascript - How can i pass a JSON array from php to JS? -
im trying populate morris.js chart set of results. in controller create array of results , use json_encode create json array, here output in view using print_r:
{"positive":7,"negative":26,"pending":786,"contact clinic":242,"misc":2} how pass morris.js chart populate chart using data label / value pairs? try either blank chart or "undefined" variable or "nan". here controller:
function execute_search() { // retrieve posted search term. $search_term = $this->input->post('search'); // results count , pass json: $data = $this->search_model->count_res('$p_results_data'); $pos = 0; $neg= 0; $pen = 0; $cont = 0; $misc = 0; foreach ($data $item) { if ($item['result'] === 'positive') { $pos++; } elseif ($item['result'] === 'negative') { $neg++; } elseif ($item['result'] === 'pending') { $pen++; } elseif ($item['result'] === 'contact clinic') { $cont++; } else { $misc++; } } $res = array("positive"=>$pos, "negative"=>$neg, "pending"=>$pen, "contact clinic"=>$cont, "misc"=>$misc); $data = json_encode($res); // use model 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 results view. $this->data['subview'] = ('user/search_results'); $this->load->view('_layout_admin', $this->data); } and morris.js:
$results = "<?php echo $chart ?>"; new morris.donut({ element: 'donuteg', data: [ $results ], }); any appreciated
in javascript, json.parse friend, assuming have json created 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 way it
in view:
<input type="hidden" id="chartdata" value='<?php echo $chart; ?>' /> in js (using jquery):
var chartdata = $('#chartdata').val(); new morris.donut({ element: 'donuteg', data: json.parse( chartdata ) }); after looking @ documentation morris.js, found how can right way:
// looking @ docs morris.js: // http://jsbin.com/ukaxod/144/embed?js,output // data, it's in 1 json object var chartdata = json.parse( $('#chartdata').val() ); // need break object parts of donut var donutparts = []; $.each( chartdata, function(k,v){ donutparts.push({ label: k, value: v }); }); // create donut morris.donut({ element: 'donuteg', data: donutparts });
Comments
Post a Comment