Morris Chart refresh issue with php data - javascript

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

Related

Do not display data output in ajax

I wrote the following code snippet for Ajax connections, but unfortunately the return value is not displayed in the output, but it does not give a special warning to understand the meaning. Please help.
js
$("#search").on('keyup', function(){var value = $(this).val();
$.ajax('feed.php',{
type: 'POST',
dataType: 'json',
data: {
keyword: value
},
success: function(data){
$("#pre").html(data);
}
});
});
feed.php
<?php
require_once('main.php');
$db = Db::getInstance();
$keyword = $_POST['keyword'];
$records = $db->query("SELECT * FROM dic_word WHERE word LIKE '%$keyword%'");
$out['html']= '';
foreach($records as $record){
$out['html'] .= $record['word'] . '<br>';
}
echo json_encode($out);
?>
js:
jQuery('#search').on('keyup', () => {
jQuery.ajax({
url: 'feed.php',
type: 'POST',
data: { keyword: jQuery(this).val() },
success: response => {
jQuery('#pre').html(response);
}
});
});
feed.php
<?php
require_once('main.php');
$database = Db::getInstance();
$keyword = $_POST['keyword'];
$records = $database->query("SELECT * FROM dic_word WHERE word LIKE '%$keyword%'");
$output = '';
foreach($records as $record){
$output .= $record['word'] . '<br />';
}
echo($output);
?>
PS: You don't need to use json output absolutly. But if there is coercion to using json output, the problem is 2 following items:
You don't set the output "Content-Type" to json: header('Content-Type: application/json');
You shouldn't pass the json object to html method in jQuery and should parsing it at first with JSON.parse(response) class, then with foreach, for or anything else process it

update Chart Js with new data onclick button

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

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

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

Populating an array through jquery AJAX in php

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

Categories