Receive data via AJAX with jQuery Flot - javascript

I have a problem with jQuery flot.
PHP output (not JSON):
[[1, 153], [2, 513], [3, 644]] ~~ [[1, 1553], [2, 1903], [3, 2680]]
jQuery call:
$.ajax({
url: 'xxx.php',
success: function (data) {
var dataArray = data.split('~~'),
dataArray1 = dataArray[0],
dataArray2 = dataArray[1],
plot = $.plot($('#xxx'), [{
data: dataArray1,
color: colours[0]
},
{
data: dataArray2,
color: colours[1],
points: {
show: true,
}
},
], {
series: {
bars: {
show: true,
barWidth: .6,
align: 'center'
}
},
grid: {
show: true,
hoverable: true,
clickable: true,
autoHighlight: true,
borderWidth: true,
borderColor: 'rgba(255, 255, 255, 0)'
},
xaxis: {
show: false
}
});
}
});
Taking the data in this way, I'm trying to use jQuery Flot but does not work...
Whereas, I can by separating data:
First label:
[[1, 153], [2, 513], [3, 644]]
Second label:
[[1, 1553], [2, 1903], [3, 2680]]

I'll share a Simple example jquery Flot with ajax for basic understanding purpose.
See this page and let change it into ajax : http://www.jqueryflottutorial.com/making-first-jquery-flot-line-chart.html
First, you must successful showing the chart as described without ajax. Don't forget to put height and width in div tag if you don't include css file.:
<div id="flot-placeholder" style="width: 100%; height: 260px"></div>
If ok, then follow this step.
STEP 1 : Put the script inside a function:
<script>
function show_chart(data) {
// this will be moved to php file
//var data = [[1, 130], [2, 40], [3, 80], [4, 160], [5, 159], [6, 370], [7, 330], [8, 350], [9, 370], [10, 400], [11, 330], [12, 350]];
var dataset = [{label: "line1",data: data}];
var options = {
series: {
lines: { show: true },
points: {
radius: 3,
show: true
}
}
};
$(document).ready(function () {
$.plot($("#flot-placeholder"), dataset, options);
});
}
</script>
STEP 2 : Create sample.php.
<?php
require 'config.php';
if($_POST)
{
$id = $_POST['id'];
$arr = array();
$arr = [[1, 130], [2, 40], [3, 80], [4, 160], [5, 159], [6, 370], [7, 330], [8, 350], [9, 370], [10, 400], [11, 330], [12, 350]];
echo json_encode($arr);
}?>
Note : $arr that moved from the first script then become only a sample data. You should make a php class or function that fetch data from database and return as array format as shown in $arr.
STEP 3 : Create simple ajax to get the response and render the chart :
var id = 1;
$.post('/..if any folder../sample.php', {
id : id,
}, function(response){
var data = JSON.parse(response);
show_chart(data); // call function and render the chart in <div id="flot-placeholder"></div>
});
Step Finish.
In some cases, we may need two or more data type. Then just add this to the code :
inside sample.php :
$arr1 = array();
$arr2 = array();
$arr1 = [[1, 130], [2, 40], [3, 80], [4, 160], [5, 159], [6, 370], [7, 330], [8, 350], [9, 370], [10, 400], [11, 330], [12, 350]];
$arr2 = [[1, 130], [2, 40], [3, 80], [4, 160], [5, 159], [6, 370], [7, 330], [8, 350], [9, 370], [10, 400], [11, 330], [12, 350]];
// put more if rquired
echo json_encode($arr1,$arr2); // put more array if required
inside ajax :
var data = JSON.parse(response);
var result1 = data[0]; // response data from $arr1
var result2 = data[1]; // response data from $arr2
Sorry for long description. Hope it will help.
Just for fun :
Some people don't want to show 'sample.php' in the console log. For this purpose we can simply change 'sample' as a folder and create index.php inside it and in the ajax we just direct the url to the folder like this :
$.post('/..if any folder../sample/'), { // this will open index.php

You have recieved a string that was not qualified as JSON data. Then you've splitted it on two strings, that are still not JSON. Then you trying to instantiate plot object with data: your_string_value. Here plot waiting of an object, not string.
Try to define data of your plot this way: data:$.parseJSON( dataArray1 )

Related

How to return 3 fields in Json and popular chart

I have a service in PHP returning the following:
[[1,"16846"],[2,"16858"],[3,"16923"],[4,"16891"]]
In my HTML I have ajax searching for this information;
$.ajax({
type: 'POST',
url: 'getDadosGrafico.php',
dataType: 'json', // use this
success: function(data) {
var dados = data;
I need my chart to have 3 records, I already have all 3 columns in the database.
How can I make ajax identify the 3 columns
My code PHP
$stmt = $con->prepare($sql);
$stmt->execute();
$users = $stmt->fetchAll();
$cont=1;
$dataset1 = array();
foreach ($users as $row) {
$data = $row['data_reenvio'];
$data_formatada=date('d/m/Y',strtotime($data));
$dataset1[] = array($cont , $row['total_sucesso'], $row['total_falha'], $row['total'] );
$cont++;
}
print (json_encode($dataset1));
My Code HTML
$.ajax({
type: 'POST',
url: 'getDadosGrafico.php',
dataType: 'json', // use this
success: function(data) {
var dados = data;
// Graph Data ##############################################
var graphData = [{
// Visits
data: dados, //[ [6, 1300], [7, 1600], [8, 1900], [9, 2100], [10, 2500], [11, 2200], [12, 2000], [13, 1950], [14, 1900], [15, 2000] ],
color: '#71c73e'
}, {
// Returning Visits
data: [ [1, 15500], [2, 16000], [3, 16550], [4, 16000], [5, 16800], [6, 16900], [7, 16800], [8, 16850], [9, 16830], [10, 17000] ],
color: '#77b7c5',
points: {
radius: 4,
fillColor: '#77b7c5'
}
}, {
// Returning Visits
data: [ [1, 17500], [2, 17000], [3, 17550], [4, 18000], [5, 18800], [6, 18900], [7, 18800], [8, 18850], [9, 18830], [10, 17000] ],
color: '#77b7c5',
points: {
radius: 4,
fillColor: '#0007c5'
}
}
];
You need to return an object with 3 properties, each one with an array of arrays, like this:
{
visits: [ [6, 1300], [7, 1600], [8, 1900], [9, 2100], [10, 2500], [11, 2200], [12, 2000], [13, 1950], [14, 1900], [15, 2000] ],
returning_visitors: [ [1, 15500], [2, 16000], [3, 16550], [4, 16000], [5, 16800], [6, 16900], [7, 16800], [8, 16850], [9, 16830], [10, 17000] ],
extra: [ [1, 17500], [2, 17000], [3, 17550], [4, 18000], [5, 18800], [6, 18900], [7, 18800], [8, 18850], [9, 18830], [10, 17000] ]
}
And then, you will use these object values on your code, like this:
var graphData = [{
// Visits
data: dados.visits
color: '#71c73e'
}, {
// Returning Visits
data: dados.returning_visitors,
color: '#77b7c5',
points: {
radius: 4,
fillColor: '#77b7c5'
}
}, {
// Returning Visits
data: dados.extra,
color: '#77b7c5',
points: {
radius: 4,
fillColor: '#0007c5'
}
}
];
On your PHP code, I'm not sure, but I think that it would be something like this:
$stmt = $con->prepare($sql);
$stmt->execute();
$users = $stmt->fetchAll();
$cont=1;
$datasetTotalSucesso = array();
$datasetTotalFalha = array();
$datasetTotal = array();
foreach ($users as $row) {
$data = $row['data_reenvio'];
$data_formatada=date('d/m/Y',strtotime($data));
$datasetdatasetTotalSucesso[] = array($cont , $row['total_sucesso']);
$datasetTotalFalha[] = array($cont , $row['total_falha']);
$datasetTotal[] = array($cont , $row['total'] );
$cont++;
}
$obj = array('visits' => $datasetdatasetTotalSucesso, 'returning_visitors' => $datasetTotalFalha, 'extra' => $datasetTotal);
print (json_encode($obj));

How to pass values dynamically to a chart

I am building an app that has a dashboard with a graphical representation of data. It's a template. I want the values to be dynamic on the chart, i.e. I want use php to pass the values to the chart.
The problem is that values are set in a '.js' file. How can i pass values from the database to the file in order to display them?
Please help
this is my html
<!-- Chart Widget -->
<div class="widget">
<div class="widget-content border-bottom">
<span class="pull-right text-muted"><?php echo htmlentities(date("Y")); ?></span>
Last Year's Data
</div>
<div class="widget-content border-bottom themed-background-muted">
<!-- Flot Charts (initialized in js/pages/readyDashboard.js), for more examples you can check out http://www.flotcharts.org/ -->
<div id="chart-classic-dash" style="height: 393px;"></div>
</div>
<!--
<div class="widget-content widget-content-full">
<div class="row text-center">
<div class="col-xs-4 push-inner-top-bottom border-right">
<h3 class="widget-heading"><i class="gi gi-wallet text-dark push-bit"></i> <br><small>$ 41k</small></h3>
</div>
<div class="col-xs-4 push-inner-top-bottom">
<h3 class="widget-heading"><i class="gi gi-cardio text-dark push-bit"></i> <br><small>17k Sales</small></h3>
</div>
<div class="col-xs-4 push-inner-top-bottom border-left">
<h3 class="widget-heading"><i class="gi gi-life_preserver text-dark push-bit"></i> <br><small>3k+ Tickets</small></h3>
</div>
</div>
</div>-->
</div>
And then this code triggers the '.js' file
<script>$(function(){ ReadyDashboard.init(); });</script>
And then this is the javascript snippet
var chartClassicDash = $('#chart-classic-dash');
// Data for the chart
var dataEarnings = [[1, 2300], [2, 2300], [3, 3200], [4, 2500], [5, 4200], [6, 3100], [7, 3600], [8, 2500], [9, 4600], [10, 3700], [11, 4200], [12, 5200]];
var dataSales = [[1, 850], [2, 750], [3, 1500], [4, 900], [5, 1500], [6, 1150], [7, 1500], [8, 900], [9, 1800], [10, 1700], [11, 1900], [12, 2550]];
var dataTickets = [[1, 130], [2, 330], [3, 220], [4, 350], [5, 150], [6, 275], [7, 280], [8, 380], [9, 120], [10, 330], [11, 190], [12, 410]];
var dataMonths = [[1, 'Jan'], [2, 'Feb'], [3, 'Mar'], [4, 'Apr'], [5, 'May'], [6, 'Jun'], [7, 'Jul'], [8, 'Aug'], [9, 'Sep'], [10, 'Oct'], [11, 'Nov'], [12, 'Dec']];
// Classic Chart
$.plot(chartClassicDash,
[
{
label: 'Sales',
data: dataEarnings,
lines: {show: true, fill: true, fillColor: {colors: [{opacity: .6}, {opacity: .6}]}},
points: {show: true, radius: 5}
},
{
label: 'Deposits',
data: dataSales,
lines: {show: true, fill: true, fillColor: {colors: [{opacity: .6}, {opacity: .6}]}},
points: {show: true, radius: 5}
},
{
label: 'Withdrawal',
data: dataTickets,
lines: {show: true, fill: true, fillColor: {colors: [{opacity: .6}, {opacity: .6}]}},
points: {show: true, radius: 5}
}
],
{
colors: ['#5ccdde', '#454e59', '#ffffff'],
//colors: ['#5ccdde', '#deb25c', '#de815c'],
legend: {show: true, position: 'nw', backgroundOpacity: 0},
grid: {borderWidth: 0, hoverable: true, clickable: true},
yaxis: {show: false, tickColor: '#f5f5f5', ticks: 3},
xaxis: {ticks: dataMonths, tickColor: '#f9f9f9'}
}
);
I want to dynamically control these values
// Data for the chart
var dataEarnings = [[1, 2300], [2, 2300], [3, 3200], [4, 2500], [5, 4200], [6, 3100], [7, 3600], [8, 2500], [9, 4600], [10, 3700], [11, 4200], [12, 5200]];
var dataSales = [[1, 850], [2, 750], [3, 1500], [4, 900], [5, 1500], [6, 1150], [7, 1500], [8, 900], [9, 1800], [10, 1700], [11, 1900], [12, 2550]];
var dataTickets = [[1, 130], [2, 330], [3, 220], [4, 350], [5, 150], [6, 275], [7, 280], [8, 380], [9, 120], [10, 330], [11, 190], [12, 410]];
Thanks once again
Please post your code, it is easy to help you, and it's simple to pass values to javascript variables through php, below is my sample code to pass dyanamic data comming from database to barchart. It is for your reference not complete code
<script type="text/javascript">
google.charts.setOnLoadCallback(drawChart);
imagepath_comparison="";
function drawChart() {
var data = google.visualization.arrayToDataTable([<?=$data;?>]);
var options = {
title: 'GRAPH ANALYSIS',
vAxis: {title: "SUBJECTS"},
hAxis: {
title: "MARKS"
}
};
</script>
ZingChart has a very compatible plugin for retrieving data and uploading it using php!
We also have several examples to help you better understand compatability
php and AJAX example
MySQL example
ZingChart php wrapper
php dashboard
php demo1
php demo2
If you want to pass data from a database to a dynamic chart, you have to use AJAX. I'd try it with jQuery AJAX.
Have a look at this: Passing data from php to Jquery
Do you have any code snippets? We may help you out, if you're not familiar with ajax.
in your php:
$sql8 = "SELECT marca, COUNT(*) as cnt, DATE_FORMAT(entra, '%m/%d/%Y') FROM equipos "
. "where entra between now() - interval 30 day and now() GROUP BY marca ORDER BY marca";
// execute SQL query and get result
$sql_result = mysql_query($sql8)
or die("Couldn't execute query.");
in your script:
data: [
<?php while($row = mysql_fetch_array($sql_result)){ ?>
{
marca: '<?php echo $row['marca']; ?>',
cnt: '<?php echo $row['cnt']; ?>',
},
<?php } ?>],
Thanks everyone, I simply used AJAX to pass the values too the JavaScript file.

How to insert values in bars (flotcharts)

I have some problems to show some values in bars. I want a chart like this: Example. I don't know what I'm missing in here.
$('#myModalChart').on('shown.bs.modal', function (e) {
var data = [{
label: "Foo",
data: [
[2],
[3, 9, 12],
[6, 0, 3],
[9, 11, 12],
[12, 0, 1],
[15, 0, 2],
[18],
[3, 12, 12],
[9, 12, 12]
]
},
{
label: "Bar",
data: [
[2],
[3, 0, 5],
[6, 3, 7],
[9, 4, 11],
[12, 1, 3],
[15, 2, 5],
[18]
]
},
{
label: "Tree",
data: [
[2],
[3, 5, 9],
[6, 7, 15],
[9, 0, 4],
[12, 3, 13],
[15, 5, 17],
[15, 17, 17],
[12, 13, 13],
[6, 15, 15],
[18]
]
},];
var options = {
series: {
bars: {
show: true,
barWidth: 1
}
},
xaxis: {
align: "center",
ticks: [
[3.5, 'text1'],
[6.5, 'text2'],
[9.5, 'text3'],
[12.5, 'text4'],
[15.5, 'text5']
]
}
};
var plot = $.plot("#chart2", data, options)
});
I want a chart like this, with labels in it. And I wish have in all of them.
What I'm missing?
You have to create and place the data value labels yourself. How to do this can be seen in this answer.
I created a fiddle adjusting it to your code. Only the first data series (foo) has labels for now. you will have to adjust the position. The relevant code:
$.each(plot.getData()[0].data, function (i, el) {
if (el.length > 1) {
var o = plot.pointOffset({
x: el[0],
y: el[1]
});
$('<div class="data-point-label">' + el[1] + '</div>').css({
position: 'absolute',
left: o.left + 4,
top: o.top,
'text-align': 'center',
display: 'none'
}).appendTo(plot.getPlaceholder()).fadeIn('slow');
}
});
But you may also have to cleanup your data. You have multiple data points with the same x values (which means bars behind / in front of each other which leads to some being invisible). Take a look at the side-by-side and stack plugins on the flot plugin page.

javascript flot threshold for dynamic data value

Here is my plot data
var data = [{
data: [[4, 80], [8, 50], [9, 130]],
color: "rgb(30, 180, 20)",
threshold: {
below: 100,
color: "rgb(200, 20, 30)"
}
}]
var bar = $.plot("#placeholder", data);
and if i change the value of data in a button click like
data= [[4, 130], [8, 50], [9, 130]];
bar.setData([data]);
bar.draw();
});
The treshold value didnt work , if there is a way to acheive this.
You aren't updating the data correctly. You are initially giving flot a series object with threshold settings, when you setData though, you are giving it an array without those settings.
Do this instead to preserve your series options:
someData = somePlot.getData();
someData[0].data = [[4, 130], [8, 50], [9, 130]];
somePlot.setData(someData);
somePlot.draw();
Here's an example.
EDITS
If you don't like the getData call, leave your master data variable in scope and update that as #Raidri hinted at:
var masterData = [{
data: [[4, 80], [8, 50], [9, 130]],
color: "rgb(30, 180, 20)",
threshold: {
below: 100,
color: "rgb(200, 20, 30)"
}
}]
// later ...
masterData[0].data = [[4, 130], [8, 50], [9, 130]];
somePlot.setData(masterData);
somePlot.draw();
The important part is to leave your threshold series options intact in the setData call.
Have you tried calling bar.setupGrid() before the bar.draw()?
If that doesn't help, you make a complete new plot:
data[0].data = [[4, 130], [8, 50], [9, 130]];
bar = $.plot("#placeholder", data)

How to use an array inside a multidimensional array?

If I have an array like so:
var phpintojsArray = [["1","20"]];
and... I also have a multid-array:
var data = [[1,20], [4, 20], [7, 55], [9, 10], [9, 10]];
how to add the phpintojsArray into the data array? I want:
var data = [[phpintojsArray], [1,20], [4, 20], [7, 55], [9, 10], [9, 10]];
What is one way to accomplish this?
Clarification -- Trying to manipulate the data in a chart
This works:
/* Bar Chart */
var data = [[1, 10],[3, 60], [5, 20], [7, 50], [9, 10]];
// Initialize Bars Chart
$.plot(BarChart, [
{ data: data, bars: { show: true, fillColor: { colors: [{ opacity: 1 }, { opacity: 1 }] } }, label: 'Example label' } ],
{
legend: {
backgroundColor: '#f6f6f6',
backgroundOpacity: 0.8
},
colors: ['#39d5db'],
grid: {
borderColor: '#cccccc',
color: '#999999',
labelMargin: 10
},
yaxis: {
ticks: 5
},
xaxis: {
tickSize: 1
}
}
);
This does Not work:
var phpintojsArray = <?= json_encode($sales); ?>;
var two = [3, 60];
var three = [5, 20];
var four = [7, 50];
var five = [9, 10];
/* Bars Chart */
var data = [[phpintojsArray], [two], [three], [four], [five]];
// Initialize Bars Chart
$.plot(BarChart, [
{ data: data, bars: { show: true, fillColor: { colors: [{ opacity: 1 }, { opacity: 1 }] } }, label: 'Example label' } ],
{
legend: {
backgroundColor: '#f6f6f6',
backgroundOpacity: 0.8
},
colors: ['#39d5db'],
grid: {
borderColor: '#cccccc',
color: '#999999',
labelMargin: 10
},
yaxis: {
ticks: 5
},
xaxis: {
tickSize: 1
}
}
);
Why?
You can use splice to insert the elements:
data.splice(0, 0, phpintojsArray);
This works:
/* Bar Chart */
var data = [[1, 10],[3, 60], [5, 20], [7, 50], [9, 10]];
This does Not work:
/* Bars Chart */
var data = [[phpintojsArray], [two], [three], [four], [five]];
Why?
Because the two expressions yield different structures. In the first one you have two levels of nested arrays (small arrays inside a big one). In the second you have three levels of nested arrays.
A simple console.log will show you the difference.
Make sure that your data is in the correct structure. Change it to:
var data = [two, three, four, five];
(In case it's still not clear, the brackets [] define a new array)
Regarding your question on how to prepend phpintojsArray, you could do:
Array.prototype.unshift.apply(data, phpintojsArray);
You could use eval in javascript.
For Example:
var data = [[eval("phpintojsArray")], [eval("two")], [eval("three")], [eval("four")], [eval("five")]];

Categories