update Chart Js with new data onclick button - javascript

I am sending a POST request to a php file to fetch new data to update my chart, although I am getting the data I needed my chart wont be updated, I can't see where the problem is in my code.
function LoadResultOnClickButton()
{
$.ajax({
type: "POST",
url: 'mydata.php',
data: {type: 'search'},
success: function(data){
var chart = new Chartist.Pie('.ct-chart-category',
{
series: data},
{
donut: true,
showLabel: false,
donutWidth: 40
}
);
}
});
}
My test data (php file)
<?php
$type=$_POST['type'];
if ($type=="search")
{
$Labels = array();
$series = array();
$Labels = ['success','Error','Disabled'];
$series = [40,20,40];
$Labels_Json = json_encode($Labels);
$Data_Json = json_encode($series, JSON_NUMERIC_CHECK);
echo $Data_Json;
}
else
{
$Labels = array();
$series = array();
$Labels = ['success','Error','Disabled'];
$series = [75,20,5];
$Labels_Json = json_encode($Labels);
$Data_Json = json_encode($series, JSON_NUMERIC_CHECK);
echo $Data_Json;
}
?>
My HTML code :
<div id="myChart" class="ct-chart-category ct-golden-section" style="height: 315px;"></div>
filtrebtn</div>
I'm sorry if my explanation is hard to understand; it was difficult for me to explain. Please ask me for any clarification you need.
Best regards

Related

Morris Chart refresh issue with php data

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();
}
});
}

Ajax call to php, get mysql data as array and use in JS function

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);
}
}
}
});
});

Ajax success need something for php JSON object

I am trying to make a user search system like facebook using ajax and php json. But i have one problem.
From the data users table have Marc Zuckerberg, Marc Zeyn, Marc Alp. I mean 3 user first name is same, so normaly when i write the Marc name then i should be get all Marc names from data. Like
<div class="ul">Marc Zuckerbert</div>
<div class="ul">Marc Zeyn</div>
<div class="ul">Marc Alp</div>
but i am not getting all Marc names just i am getting one marc result. Chrome developer console show me all Marc name but not show my within HTML. I think i need some code from ajax success.
JS
$('body').delegate('#searchkey','keyup', function(){
clearTimeout(timer);
timer = setTimeout(function(){
var box = $('#searchkey').val();
contentbox = $.trim(box);
var dataString = 'keys=' + contentbox;
if(contentbox !==''){
$.ajax({
type: "POST",
url: siteurl +"requests/search.php",
data: dataString,
dataType:"json",
cache: false,
beforeSend: function(){},
success: function(data){
$('.un').html(data.username);
$('.uf').html(data.fullname);
}
});
}
});
});
search.php
<?php
include_once 'inc.php';
if(isset($_POST['keys'])) {
$keys = mysqli_real_escape_string($db, $_POST['keys']);
$keyRestuls = $WidGet->SearchUser($keys);
if($keyRestuls) {
// If array is in data
foreach($keyRestuls as $datas) {
$dataUsername = $datas['username'];
$dataUserID = $datas['fullname'];
$data = array(
'username' => $dataUsername,
'fullname' => $dataUserID
);
echo json_encode( $data );
}
}
}
?>
SearchUser function is here
public function SearchUser($keys){
$keys = mysqli_real_escape_string($this->db, $keys);
$result = mysqli_query($this->db,"SELECT
username,
uid,
fullname FROM
users WHERE
username like '%{$keys}%' or fullname like '%{$keys}%'
ORDER BY uid LIMIT 10") or die(mysqli_error($this->db));
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC)) {
$data[]=$row;
}
if(!empty($data)) {
// Store the result into array
return $data;
}
}
Your PHP script is generating a malformed JSON
{"username":"marc1","fullname":"Marc Zuckerberg"}
{"username":"marc3","fullname":"Marc Zeyn"}
{"username":"marc2","fullname":"Marc Alp"}
It shoulds generate
[
{"username":"marc1","fullname":"Marc Zuckerberg"},
{"username":"marc3","fullname":"Marc Zeyn"},
{"username":"marc2","fullname":"Marc Alp"},
]
You can fix it by appending to an array instead of writting each row independamently
foreach($keyRestuls as $datas)
{
$dataUsername = $datas['username'];
$dataUserID = $datas['fullname'];
$data[] = array(
'username' => $dataUsername,
'fullname' => $dataUserID
);
}
echo json_encode( $data );
And then you'll have to loop over $data in your JS, I suggest you use $.each
function success(data) {
$.each(data, function(key, value) {
console.log(value.username + ": " + value.fullname);
})
}

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
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
});

PHP json to google chart api

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;

Categories