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
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.
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
});
Related
I'm struggling with Morris charts for some time now, I would like to update my Morris chart onclick button event with php data.
I start by loading data like below, I include first my php page, but nothing happen when I try to load new data on click :(
<?php include ('loadchart.php');?>
var graph = new Morris.Area({
element: 'morris_area',
xkey: 'x',
ykeys: ['y', 'z'],
lineColors: ['#5969ff', '#ff407b'],
resize: true,
gridTextSize: '14px'
});
graph.setData([<?php echo $data; ?>]);
graph.redraw();
Until then all is well :D but when I try to load the below php data nothing happen :
"{x:'2018-03-20',y:1,z:7}, {x:'2018-03-22',y:31,z:5}, {x:'2018-03-25',y:7,z:21}"
generated like below
<?php
$uname = $_POST["type1"];
if ($uname=='search1')
{
$var1= '2018-03-20';
$var2= 1;
$var3= 7;
$chart_data1 = '';
$chart_data1 .= "{x:'".$var1."',y:".$var2.",z:".$var3."}, ";
$var11= '2018-03-22';
$var22= 31;
$var33= 5;
$chart_data1 .= "{x:'".$var11."',y:".$var22.",z:".$var33."}, ";
$var111= '2018-03-25';
$var222= 7;
$var333= 21;
$chart_data1 .= "{x:'".$var111."',y:".$var222.",z:".$var333."}, ";
$chart_data1 = substr($chart_data1, 0, -2);
echo json_encode($chart_data1);
}
?>
my AJAX code :
function Onclickbutton()
{
$.ajax({
type: "POST",
url: 'admin/Mynewdata.php',
data: {type1: 'search1'},
success: function(data){
alert(data);
graph.setData(data);
graph.redraw();
}
});
}
Any help would be appreciative :)
I think the crux of your issue is that the JSON you are manually creating is not valid.
Try creating an array of your values before passing that array to json_encode:
$arr= array();
$arr[] = array('x'=>'2018-03-20', 'y'=>1, 'z'=>7);
$arr[] = array('x'=>'2018-03-22', 'y'=>31, 'z'=>5);
$arr[] = array('x'=>'2018-03-25', 'y'=>7, 'z'=>21);
echo json_encode($arr);
I found a workaround :D, I create an new array in my js code , thank you for you help
function LoadResultMorris()
{
$.ajax({
type: "POST",
url: 'admin/data.php',
data: {type1: 'search1'},
success: function(data){
var array1 = [];
var i=0;
$.each(JSON.parse(data), function(key,obj) {
array1[i] = {};
array1[i]['x']=obj.x;
array1[i]['y']=obj.y;
array1[i]['z']=obj.z;
i++;
});
graph.setData(JSON.stringify(array1));
graph.redraw();
}
});
}
I'm looking to make an ajax call to a PHP script to get data from MySQL, create a json array and pass it back to the success function of the ajax call, where i will then use it as parameters for a JavaScript function.
This is my ajax call,
$('button[name="message"]').click(function() {
var $row = $(this).closest("tr"); // Find the row
var $tenant_id = $row.find(".col-md-1 id").text(); // Find the tenants ID
var $landlord_id = "<?php echo $id; ?>"
$.ajax({
url : "./message.php",
type : "POST",
async : false,
data: {
landlord_id: $landlord_id,
tenant_id : $tenant_id
},
success: function(data){
console.log(data);
var messages = data;
insertChat(messages.sender_id, messages.body, messages.timestamp);
}
})
});
And this is my PHP file,
<?php
session_start();
require_once('../dbconnect.php');
// update tenants table to show deposit returned
if(isset($_POST['tenant_id'])){
$tenant_id = $_POST['tenant_id'];
$landlord_id = $_POST['landlord_id'];
$sql = "SELECT * from messages WHERE messages.sender_id OR messages.receiver_id = '$tenant_id' AND messages.sender_id OR messages.receiver_id = '$landlord_id'";
$result = mysqli_query($conn, $sql) or die("Error in Selecting " . mysqli_error($conn));
//create an array
$messages = array();
while($row =mysqli_fetch_assoc($result))
{
$messages[] = $row;
}
echo json_encode($messages);
}
?>
If anybody has a link to a tutorial or the individual parts that would be fantastic. I don't even know if the process i have outlined above is correct.
If anybody could tell me the correct way to go about this that would be of great help!
Thanks
Just a few things to adjust your javascript side (I won't explain the php sql injection issue you have... but please research prepare, bind_param and execute):
Since you are returning an ARRAY of $messages from php (json_encoded), you need to loop on those in your success handler.
Add dataType: 'JSON' to your options, so it explicitly expects json returned from php.
And you were missing a couple semicolons ;)
Adjustments added to your code:
$('button[name="message"]').click(function() {
var $row = $(this).closest("tr");
var tenant_id = $row.find(".col-md-1 id").text();
var landlord_id = "<?php echo $id; ?>";
$.ajax({
url : "./message.php",
type : "POST",
data: {
landlord_id: landlord_id,
tenant_id : tenant_id
},
dataType: 'JSON',
success: function(data){
console.log(data);
if (typeof data !== undefined) {
for(var i = 0; i < data.length; i++) {
insertChat(data[i].sender_id, data[i].body, data[i].timestamp);
}
}
}
});
});
I have a function in a compare.php that takes a parameter $data and uses that data to find certain things from web and extracts data and returns an array.
function populateTableA($data);
So to fill array I do this
$arrayTableA = populateTableA($name);
now this array is then used to iterate tables..
<table id="tableA">
<input type="text" name="search"/><input type="submit"/>
<?php foreach($arrayTableA as $row) { ?>
<tr>
<td><?php echo $row['name']?></td>
<td><?php echo $row['place']?></td>
</tr>
</table>
Now what I want to do is to enter some data on input and then through jquery ajax
function populateTableA($data);
should be called and $array should be refilled with new contents and then populated on tableA without refreshing the page.
I wrote this jquery but no results.
$(document).on('submit',function(e) {
e.preventDefault(); // Add it here
$.ajax({ url: 'compare.php',
var name = ('search').val();
data: {action: 'populateTableA(name)'},
type: 'post',
success: function(output) {
$array = output;
}
});
});
I have been doing web scraping and the above was to understand how to implement that strategy... original function in my php file is below
function homeshoppingExtractor($homeshoppingSearch)
{
$homeshoppinghtml = file_get_contents('https://homeshopping.pk/search.php?category%5B%5D=&search_query='.$homeshoppingSearch);
$homeshoppingDoc = new DOMDocument();
libxml_use_internal_errors(TRUE);
if(!empty($homeshoppinghtml)){
$homeshoppingDoc->loadHTML($homeshoppinghtml);
libxml_clear_errors();
$homeshoppingXPath = new DOMXPath($homeshoppingDoc);
//HomeShopping
$hsrow = $homeshoppingXPath->query('//a[#class=""]');
$hsrow2 = $homeshoppingXPath->query('//a[#class="price"]');
$hsrow3 = $homeshoppingXPath->query('(//a[#class="price"])//#href');
$hsrow4 = $homeshoppingXPath->query('(//img[#class="img-responsive imgcent"])//#src');
//HomeShopping
if($hsrow->length > 0){
$rowarray = array();
foreach($hsrow as $row){
$rowarray[]= $row->nodeValue;
// echo $row->nodeValue . "<br/>";
}
}
if($hsrow2->length > 0){
$row2array = array();
foreach($hsrow2 as $row2){
$row2array[]=$row2->nodeValue;
// echo $row2->nodeValue . "<br/>";
}
}
if($hsrow3->length > 0){
$row3array = array();
foreach($hsrow3 as $row3){
$row3array[]=$row3->nodeValue;
//echo $row3->nodeValue . "<br/>";
}
}
if($hsrow4->length > 0){
$row4array = array();
foreach($hsrow4 as $row4){
$row4array[]=$row4->nodeValue;
//echo $row3->nodeValue . "<br/>";
}
}
$hschecker = count($rowarray);
if($hschecker != 0) {
$homeshopping = array();
for($i=0; $i < count($rowarray); $i++){
$homeshopping[$i] = [
'name'=>$rowarray[$i],
'price'=>$row2array[$i],
'link'=>$row3array[$i],
'image'=>$row4array[$i]
];
}
}
else{
echo "no result found at homeshopping";
}
}
return $homeshopping;
}
As mentioned in the comments PHP is a server side language so you will be unable to run your PHP function from javascript.
However if you want to update tableA (without refreshing the whole page) you could create a new PHP page that will only create tableA and nothing else. Then you could use this ajax call (or something similar) -
$(document).on('submit','#formReviews',function(e) {
e.preventDefault();
$.ajax({
url: 'getTableA.php', //or whatever you choose to call your new page
data: {
name: $('search').val()
},
type: 'post',
success: function(output) {
$('#tableA').replaceWith(output); //replace "tableA" with the id of the table
},
error: function() {
//report that an error occurred
}
});
});
Hi You are doing it in wrong way.You must change your response to html table and overwrite older one.
success: function(output) {
$("#tableA").html(output);
}
});
In your ajax page create a table with your result array
You are in a very wrong direction my friend.
First of all there are some syntax error in your JS code.
So use JavaScript Debugging
to find where you went wrong.
After that Basic PHP with AJAX
to get a reference how ajax and PHP work together
Then at your code
Create a PHP file where you have to print the table part which you want to refresh.
Write an AJAX which will hit that PHP file and get the table structure from the server. So all the processing of data will be done by server AJAX is only used for request for the data and get the response from the server.
Put the result in your html code using JS.
Hope this will help
i want to pre-poulate my fullcalendar instance via a php json feed.
The page is loading fine (no 404 or sth like that) but the calendar is not showing any of the events.
generating the json:
<?php
require("../config/config.php");
$uid = $_SESSION['uid'];
$res = $db->query("SELECT * FROM slots WHERE tid = '$uid'");
$data = array();
while($row = $res->fetch_assoc())
{
$event = array();
$event['editable'] = false;
$event['id'] = "fixE_".$row['id'];
$event['title'] = getSlotStatus($row['status']);
$event['sid'] = $row['sid'];
$event['status'] = $row['status'];
$event['start'] = $row['start'];
$event['end'] = $row['end'];
$event['standby'] = $row['standby'];
if(strpos($data['status'],"_old"))
{
$event['textColor'] = '#000000';
$event['color'] = '#cccccc';
$event['className'] = 'lessonSlotOld';
}
else
{
$event['color'] = getColorCode($row['status']);
if($row['standby'])
{
$event['borderColor'] = '#0000FF';
}
}
$data[] = $event;
}
echo json_encode(array("events"=>$data));?>
and here's the part of the fullcalendar code where i am inserting the feed:
events:
{
url: 'include/fetchSlots.php',
type: 'POST',
error: function(){alert("There was an error fetching events")}
},
the json output of the php looks like the following (this is just a part because the whole response would be too much ;) )
{"events":[{"editable":false,"id":"fixE_164","title":"Slot is closed","sid":"0","status":"closed","start":"2015-06-06T04:00:00+08:00","end":"2015-06-06T04:30:00+08:00","standby":"0","color":"#B20000"}]}
Ok so here's the solution/the mistake.
The only problem that fullcalendar has is the line where the actual json is posted:
echo json_encode(array("events"=>$data));
fullcalendar doesnt want the "events" and it doesnt want the twice wrapped array. so the solution to this is simply to output the data-array directly:
echo json_encode($data);
then, the events are all loaded correctly.
ah and for all watchmen out there, yes i found the mistake with the wrong named variable ;)
if(strpos($data['status'],"_old"))
to
if(strpos($row['status'],"_old"))
I'm having trouble parsing my php generated json array to a google chart. I have included Jquery, but some how i can't figure out how to parse my json data. I run a MySQL query to retrieve data from the database. Then i encode the query result with php json_encode.
I use ajax to get the json data from my php file.
getData.php:
<?php
function get_meta_values( $key, $type = 'workout', $status = 'publish' ) {
global $wpdb;
$user_ID = get_current_user_id();
if ( empty( $key ) )
return;
$r = $wpdb->get_results(
$wpdb->prepare( "
SELECT pm.meta_value, p.post_date FROM {$wpdb->postmeta} pm
LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id
INNER JOIN $wpdb->term_relationships
ON (p.ID = $wpdb->term_relationships.object_id)
INNER JOIN $wpdb->term_taxonomy
ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
WHERE pm.meta_key = '%s'
AND $wpdb->term_taxonomy.taxonomy = 'category'
AND $wpdb->term_taxonomy.term_id IN (4)
AND p.post_status = '%s'
AND p.post_type = '%s'
AND p.post_author = $user_ID
ORDER BY pm.meta_value DESC ",
$key,
$status,
$type));
if ( $r ) {
$user_ids = wp_list_pluck( $r, 'post_date' );
cache_users( $user_ids );
}
return $r;
}
$workout_history = get_meta_values( '1_rep', 'workout' );
echo json_encode($workout_history);
?>
The page that holds the chart:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "http://localhost:41175/wp-content/themes/wordpress-bootstrap-master/getData.php",
dataType: "json",
async: false
}).responseText;
var obj = window.JSON.stringify(jsonData);
var data = google.visualization.arrayToDataTable(obj);
var options = {
title: 'Test'
};
var chart = new google.visualization.LineChart(
document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
When i try to echo my json file it looks like this:
[
{
"meta_value":"999",
"post_date":"2014-04-12 18:21:51"
},
{
"meta_value":"1",
"post_date":"2014-04-12 18:58:20"
}
]
Any suggestions to what i am doing wrong?
https://developers.google.com/chart/interactive/docs/reference#google.visualization.arraytodatatable
Seems that your JSON dataset is incorrect for use with that method. It should be (in javascript):
var data = [
['metavalue', 'post_date'],
['999', '2014-04-12 18:21:51'],
['1', '2014-04-12 18:58:20']
]
which in JSON equals to:
[["metavalue","post_date"],["999","2014-04-12 18:21:51"],["1","2014-04-12 18:58:20"]]
As I have no clue where $workout_history is coming from I can't help you out with how get to that.
Your object graph is incorrect before you return $r do this:
$results = array();
$result[] = array_values($r);
return $result;
alternatively you can build an your array of array like this:
$results = array();
$result[] = array($r['message_type'], $r['post_date']);
return $result;