How I can insert array value in php and mysql from variable Var s1, s2, s3:
$(function () {
var s1 = [100, 200, 300]; //How to Get Value from mysql database
var s2 = [30, 80, 90]; //How to Get Value from mysql database
var s3 = [120, 90, 80]; //How to Get Value from mysql database
// Can specify a custom tick Array.
// Ticks should match up one for each y value (category) in the series.
var ticks = ['2010', '2011', '2012'];
var plot1 = $.jqplot('chart3', [s1, s2, s3], {
// The "seriesDefaults" option is an options object that will
// be applied to all series in the chart.
seriesDefaults: {
shadow: true, // show shadow or not.
renderer: $.jqplot.BarRenderer,
rendererOptions: {
fillToZero: true
}
},
// Custom labels for the series are specified with the "label"
// option on the series option. Here a series option object
// is specified for each series.
series: [
{label: 'Hotel'},
{label: 'Event Regristration'},
{label: 'Airfare'}
],
// Show the legend and put it outside the grid, but inside the
// plot container, shrinking the grid to accomodate the legend.
// A value of "outside" would not shrink the grid and allow
// the legend to overflow the container.
legend: {
show: true,
placement: 'outsideGrid'
},
axes: {
// Use a category axis on the x axis and use our custom ticks.
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
ticks: ticks
},
// Pad the y axis just a little so bars can get close to, but
// not touch, the grid boundaries. 1.2 is the default padding.
yaxis: {
pad: 1.05,
tickOptions: {
formatString: '$%d'
}
}
},
grid: {
borderColor: '#000', // CSS color spec for border around grid.
borderWidth: 2.0, // pixel width of border around grid.
shadow: true // draw a shadow for grid.
}
});
// Bind a listener to the "jqplotDataClick" event. Here, simply change
// the text of the info3 element to show what series and ponit were
// clicked along with the data for that point.
$('#chart3').bind('jqplotDataClick',
function (ev, seriesIndex, pointIndex, data) {
$('#info3').html('series: ' + seriesIndex + ', point: ' + pointIndex + ', data: ' + data);
});
});
2 ways:
Ajax
Use: $.getJSON ( http://api.jquery.com/jQuery.getJSON/ )
var ses = {};
$.getJSON('page_adress.php', {variable_you_want_to_pass1: 'its value', variable_you_want_to_pass2: 'var 2 value'}, function(data) {
ses = data;
});
In your PHP:
<?php
$passed_var_1 = $_REQUEST['variable_you_want_to_pass1'];
//.... etc
//Here you get your data from mysql, cast it into array
header('Content-type: application/json');
echo json_encode($dbdata);
?>
So basically after request finishes you will have exact array you had in PHP transferred in JavaScript. Have in mind that this technique uses AJAX. If you want to avoid that, you will have to use second technique.
Dynamically Creating JS
Make PHP generate your javascript. In this case you would have in your main page
<script src="js_data.js.php" type="text/javascript"></script>
In your js_data.js.php file:
<?php
header("content-type: application/x-javascript");
$s1 = array(100,200,300);
//....
var s1 = [<?=implode(', ', $s1)?>],
s2 = [<?=implode(', ', $s2)?>],
s3 = [<?=implode(', ', $s3)?>];
?>
First method (w/o ajax & json)(untidy-way)
First fetch the value from database and have it in PHP variable.
Then put html element in page and assign the value to it.
Then use it in javascript using document.getElement method.
// assume that you have got value from database in $valueFrmDB.
$valueFrmDB;
Now, take html element(you might have to take more than one)
<input type="hidden" id="something" name="something" value="echo value of $valueFrmDB here" />;
Then, in javascript
var vfd = document.getElementById('something').value;
convert string to array
Second method(with ajax and json)(simple & correct but must know ajax and json)
Use ajax to fetch the values from database
Then use json to pass that values to javascript
simply you can do this by:
<?php
$query = mysql_query("SELECT * FROM attendence");
$results = array(array());
while($line = mysql_fetch_array($query)){
$results[] = $line;
}
?>
Javascript
<script type="text/javascript">
$(document).ready(function(){
var data = <?php echo json_encode($results); ?>; //array uses here
var plot1 = jQuery.jqplot ('chart1', [data],
{
seriesDefaults: {
renderer: jQuery.jqplot.PieRenderer,
rendererOptions: {
showDataLabels: true}
},
legend: { show:true, location: 'e' }
});
});
</script>
Related
`<script>
Chart.pluginService.register({
beforeDraw: function (chart) {
var width = chart.chart.width,
height = chart.chart.height,
ctx = chart.chart.ctx;
ctx.restore();
var fontSize = (height / 114).toFixed(2);
ctx.font = fontSize + "em sans-serif";
ctx.textBaseline = "middle";
var text = chart.config.options.elements.center.text,
textX = Math.round((width - ctx.measureText(text).width) / 2),
textY = height / 2;
ctx.fillText(text, textX, textY);
ctx.save();
}
});
// chart1
var data = {
labels: ["Red", "Blue"],
datasets: [{
data: [50],
backgroundColor: ["#BEFF60", "#36A2EB"],
hoverBackgroundColor: ["#BEFF60", "#36A2EB"]
}]
};
var promisedDeliveryChart = new Chart(document.getElementById('myChart1'), {
type: 'doughnut',
data: data,
options: {
title: {
display: true,
text: 'OEE Chart'
},
elements: {
center: {
text: parseInt(<?php echo json_encode($OEE); ?>) + '%', //set as you wish
}
},
cutout Percentage: 85,
legend: {
display: false
}
}
});
</script>
`
I have few questions here.
I have already created Plugins Service and doughnut chart code where I standardize everything including having a text in between the doughnut chart - how can I small changes the Plugin Service so that where I can add picture send towards backwards and bring the text infront?? - Is it possible this same Plugin Service used after modification answers given by anyone where for other charts but dont want to add the picture and text as other charts will be either bar graph or line chart etc... can anyone guide me with these kind of things. I'm not sure how to do it.. any advice??
If lets say I want to do chartsJS for stepped line chart how is that?? I tried using the same Plugin Service but failed. if if each type of chart need to use different plugins I can do it... but the issue I will create their separate files and call them in PHP index folder (as the main file running the website but when I add the JavaScript link and add call the name from the JS file into the PHP index file failed. Hopefully someone can guide me or advice me on this
when i use the same PluginService(which is used for doughnut chart) i cannot show the results for barchart , line chart etc using the same PluginService when i pass <php json() file ?> from the database file i created to pass the data into data[] in chartJS
-dscsccsss\\\\\\
I want implement price based slider in my project but i don't have any idea how to implement. So, anyone can help me please. I want look like like this(but it should be in php):
http://www.aspsnippets.com/Demos/772/
http://demos.telerik.com/aspnet-ajax/slider/examples/rangeslider/defaultcs.aspx
Here, i give an example for you to start, i'm using Jquery UI for range slider :
Consider this HTML element for rendering slider range
<p>
<label for="amount">Price range:</label>
<input type="text" id="amount" readonly style="border:0; color:#f6931f; font-weight:bold;">
</p>
<div id="slider-range"></div>
Js code :
$("#slider-range").slider({
range: true,
min: 0,
max: 500,
values: [75, 300],
slide: function (event, ui) {
// first range input(min)
var firstValue = ui.values[0];
// second range input(max)
var secondValue = ui.values[1];
$("#amount").val("$" + firstValue + " - $" + secondValue);
// here you need to get data from database
// request to php page with database queries for processing
$.ajax({
type: 'POST',
url: 'phpProcess.php', // create this file with php+mysql(any db)
data: {
first: firstValue, // send this paramter
second: secondValue // send this parameter
},
dataType : 'json',
success: function (data) { // on success request
// remember we use echo json_encode($data); in php page
// those data supposed to be available here
// try console.log(data) to view data
// on success, populate data into any type of HTML element
// either li, table, etc... something like this
}
});
}
});
// initial code to display values
$("#amount").val("$" + $("#slider-range").slider("values", 0) +
" - $" + $("#slider-range").slider("values", 1));
PHP page
// retrieve data from ajax request
$first = $_POST['first'];
$second = $_POST['second'];
// this is just an example to select data between min and max
$getData = mysqli_query($con, "SELECT *FROM products WHERE price BETWEEN '$first' AND '$second'");
$data = mysqli_fetch_array($getData);
// this output will available on success ajax callback
echo json_encode($data);
DEMO - Did't added for ajax request(Using jQuery UI)
DEMO 1 - Using ion.rangeSlider.
I am currently using D3.js to make a pie graph. The data is stored in a MSSQL database, which is then converted to JSON using PHP. Here is my code that does that
<?php
// Server Name
$myServer = "SRVR";
// Database
$myDB = "TestDB";
// If using Windows Authentication, get rid of, "'UID'=>$myUser, 'PWD'=>$myPass, "
// Notice that the latest driver uses sqlsrv rather than mssql
$conn = sqlsrv_connect('Database'=>$myDB));
// Change TestDB.vwTestData to YOURDB.dbo.YOURTABLENAME
$sql = "SELECT col, SUM(num) AS 'value'
FROM db
GROUP BY col";
$result = array();
do {
while ($row = sqlsrv_fetch_array($data, SQLSRV_FETCH_ASSOC)){
$result[] = $row;
}
} while ( sqlsrv_next_result($data) );
// This will output in JSON format if you try to hit the page in a browser
echo json_encode($result);
sqlsrv_free_stmt($data);
sqlsrv_close($conn);
?>
This works fine. I've tested it, and it outputs JSON in something like this:
[{"col":null,"value":247.9042254},{"col":"value1","value":16.8151576061},{"col":"value2","value":235.4833175609},{"col":"value3","value":2316.072432028},{"col":"value4","value":8904.4001532729}]
How can I put this in the graph? Here is my .js code
(function() {
var width = 960,
height = 500,
radius = Math.min(width, height) / 2;
var color = d3.scale.ordinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b"]);
var arc = d3.svg.arc()
.outerRadius(radius - 10)
.innerRadius(0);
var pie = d3.layout.pie()
.sort(null)
.value(function(d) { return // Something goes here I assume });
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
d3.json("scripts/graphs/script.php", function(error, data) {
data.forEach(function(d) {
// Something needs to go here?
});
var g = svg.selectAll(".arc")
.data(pie(data))
.enter().append("g")
.attr("class", "arc");
g.append("path")
.attr("d", arc)
.style("fill", function(d) { return color(d.data.age); });
g.append("text")
.attr("transform", function(d) { return "translate(" + arc.centroid(d) + ")"; })
.attr("dy", ".35em")
.style("text-anchor", "middle")
.text(function(d) { return d.data.age; });
});
})();
If someone could help me out, that would be great. Thanks!
I figured it out. I used this code and customized it for JSON
https://gist.github.com/enjalot/1203641
Here is what I got
(function() {
var w = 670, //width
h = 326, //height
r = 150, //radius
color = d3.scale.category20c(); //builtin range of colors
d3.json("script.php", function (data) {
var vis = d3.select("body")
.append("svg:svg") //create the SVG element inside the <body>
.data([data]) //associate our data with the document
.attr("width", w) //set the width and height of our visualization (these will be attributes of the <svg> tag
.attr("height", h)
.append("svg:g") //make a group to hold our pie chart
.attr("transform", "translate(" + r + "," + r + ")") //move the center of the pie chart from 0, 0 to radius, radius
var arc = d3.svg.arc() //this will create <path> elements for us using arc data
.outerRadius(r);
var pie = d3.layout.pie() //this will create arc data for us given a list of values
.value(function(d) { return d.value; }); //we must tell it out to access the value of each element in our data array
var arcs = vis.selectAll("g.slice") //this selects all <g> elements with class slice (there aren't any yet)
.data(pie) //associate the generated pie data (an array of arcs, each having startAngle, endAngle and value properties)
.enter() //this will create <g> elements for every "extra" data element that should be associated with a selection. The result is creating a <g> for every object in the data array
.append("svg:g") //create a group to hold each slice (we will have a <path> and a <text> element associated with each slice)
.attr("class", "slice"); //allow us to style things in the slices (like text)
arcs.append("svg:path")
.attr("fill", function(d, i) { return color(i); } ) //set the color for each slice to be chosen from the color function defined above
.attr("d", arc); //this creates the actual SVG path using the associated data (pie) with the arc drawing function
arcs.append("svg:text") //add a label to each slice
.attr("transform", function(d) { //set the label's origin to the center of the arc
//we have to make sure to set these before calling arc.centroid
d.innerRadius = 0;
d.outerRadius = r;
return "translate(" + arc.centroid(d) + ")"; //this gives us a pair of coordinates like [50, 50]
})
.attr("text-anchor", "middle") //center the text on it's origin
.text(function(d, i) { return data[i].col; }); //get the label from our original data array
})
})();
So what was wrong was that I wasn't connecting the key values from the JSON, to the variables in the JS. Here are the lines to change:
var vis = d3.select("<PUT DIV ID HERE>")
.value(function(d) { return d.<PUT NUMBER VALUE KEY NAME HERE>; });
.text(function(d, i) { return data[i].<PUT SLICE CATEGORY HERE>; });
I am not entirely certain what is not working about your code, but you could try something simple like:
d3.json("scripts/graphs/script.php", function(error, data) {
data.forEach(function(d) {
d.value = +d.value
});
var g...
Alternately, could you just call the php script and store the returned json object in a variable, then pass that variable to d3.json?
Hello I am getting my data from csv file and I am using 'this.update(0)' on my chart to update any point through a mouse click therefore making that point equal to 0 on y axis but what I want is that when I click on a point it first gets me the index of that point and then reload the data again from same csv file but this time the data values should not go beyond the index. e.g if I clicked on a point at x=10 then I should be able to reload the data again from file till x=9 and store the newly loaded data to an array.
Here is a part my code where data has to be reloaded. It reloads the entire data which is not need, that's probably I am not getting the right index or if there is someother problem kindly help. Thank you.
plotOptions: {
series: {
cursor: 'pointer',
point: {
events: {
click: function() {
var x= this.update(0);
$.get('testFile.csv', function(data) {
var lines = data.split('\n');
$.each(lines, function(lineNo, line) {
var items = line.split(',');
var series = {
data: []
};
$.each(items, function(itemNo, item) {
if(itemNo<x){
series.data.push(parseFloat(item)); } });
options.series.push(series);
});
var chart = new Highcharts.Chart(options);
});
To get index use: this.series.processedXData.indexOf(this.x)
Now, remove creating new chart, but instead update each of points with values, something like this:
var actSeries = this.series; //needed for scope range
...
...
...
$.each(items, function(itemNo, item) {
if(itemNo<x){
actSeries.data[itemNo].update(parseFloat(item), false);
});
});
actSeries.chart.redraw();
I am trying to plot a chart (Spline) using data that is dynamically generated from PHP. The JavaScript library I am using for this purpose is HighCharts.
The PHP generates an array of values in the format like
array(
array("1304294461000",69,"1304899261000",28),
array("1304294431000",3,"1304899161000",32)
)
which I am then passing onto a javascript array using json_encode. However, when I push these values as data, it doesn't seem to be working.
For example, here's an example with relevant code snippets like -
var namesArr = <?php echo json_encode($namesArr); ?>;
var progressTrendsData = <?php echo json_encode($progressTrendsData); ?>;
var chart;
var options = {
chart: {
renderTo: 'trendsDiv',
type: 'spline'
},
series: [{
name: '',
data: []
}]
};
for(var i=0;i<namesArr.length;i++) {
options.series.push({
name: namesArr[i],
data: progressTrendsData[i]
});
}
chart = new Highcharts.Chart(options);
The options contain other relevant data needed for the chart of course.
However, the only thing the above code is doing is plotting a single value at the date January 1 irrespective of the actual data that is being pushed.
I would tend to agree w/Mark on this. It is hard to tell exactly your data is supposed to end up looking like though. Try looking at the data loading portion of the ajax data example on the highcharts demo page.
UPDATE:
Try the following pseudocode:
var chart;
var options = {
chart: {
renderTo: 'trendsDiv',
type: 'spline'
},
series: [{
name: '',
data: []
}]
};
var seriesInfo=[];
seriesInfo[0]={"name":"Series A","data":[]};
seriesInfo[1]={"name":"Series B","data":[]};
//Loop over the series and populate the data
seriesInfo[0].data.push({x:<insert Series A timestamp>,y:<insert Series A y value>});
seriesInfo[1].data.push({x:<insert Series B timestamp>,y:<insert Series B y value>});
options.series.push(seriesInfo[0]);
options.series.push(seriesInfo[1]);
chart = new Highcharts.Chart(options);