I want to ask how to the repeat a region in javascript?
The data are dynamic and I want to find all items through php do...while loop:
<script type="text/javascript">
window.onload = function () {
<?php do{ ?>
var chart<?php echo $row_RecAllAnswers['q_id']; ?> = new CanvasJS.Chart("<?php echo $row_RecAllAnswers['q_id']; ?>", {
theme: "theme2",//theme1
title:{
text: "No. " + "<?php echo $row_RecAllAnswers['q_id']; ?>"
},
animationEnabled: true, // change to true
data: [
{
// Change type to "bar", "splineArea", "area", "spline", "pie",etc.
type: "column",
dataPoints: [
{ label: "A" , y: <?php echo $row_RecAllAnswers['A']; ?> },
{ label: "B", y: <?php echo $row_RecAllAnswers['B']; ?> },
{ label: "C", y: <?php echo $row_RecAllAnswers['C']; ?> },
{ label: "D", y: <?php echo $row_RecAllAnswers['D']; ?> }
]
}
]
});
chart<?php echo $row_RecAllAnswers['q_id']; ?>.render();
chart<?php echo $row_RecAllAnswers['q_id']; ?> = {};
window.alert(<?php echo $row_RecAllAnswers['q_id']; ?>);
<?php } while ($row_RecAllAnswers = mysql_fetch_assoc($RecAllAnswers)); ?>
}
</script>
Use json_encode to convert your mysql query result to JSON.
Write the JSON to your HTML.
In Javascript use a foreach on the JSON array to iterate.
json encode that php array into a javascript variable and then loop through that variable. In twig I do it like this:
var objectName = {{ phpVariable|json_encode|raw }};
so I think this should work find in PHP (did not test it):
var objectName = <?php echo json_encode($phpVariable); ?>;
Then the javascript variable 'objectName' will contain your data and now you can use regular javascript to loop through the data. You can also use underscore as it is easier.
_.each(objectName, function(item, key){
//do stuff here
});
Related
I am trying to draw two graphs using chartjs. I want to make my life simplier by using a for loop to declare the variables required for the chart object.
The thing is I have created a 2d array, with each row storing data for current year, the next row storing data for the consecutive year and so on. I am trying to access the row of the variable using loop.
Here is my Chart obj
var canvas6= {
type: 'doughnut',
data: {
datasets: [{
data: [
<?php
for($i=0;$i<count($dataAgeGrp[1]);$i++){ -------->Note here
echo $dataAgeGrp[1][$i]; -------->And here
echo ',';
}
?>
],
backgroundColor: [
<?php
for($i=0;$i<count($ageCategory);$i++){
$rand = str_pad(dechex(rand(0, 0xFFFF00)), 6, 0, STR_PAD_LEFT);
echo('"#' . $rand.'"');
echo ",";
}
?>
],
label: 'Pie Chart'
}],
labels: [
<?php
for($i=0;$i<count($ageCategory);$i++){
echo $ageCategory[$i];
echo ',';
}
?>
],
},
options: {
responsive: true
}
};
$(function () {
var ctx126 = document.getElementById('canvas6').getContext('2d');
window.myPie = new Chart(ctx126 , canvas6);
});
So, I tried something like this
for(var k=0;k<3;k++){
var q=26;
var canvas+q = {
type: 'doughnut',
data: {
datasets: [{
data: [
<?php
for($i=0;$i<count($dataAgeGrp[k]);$i++){
echo $dataAgeGrp[k][$i];
echo ',';
}
?>
],
backgroundColor: [
<?php
for($i=0;$i<count($ageCategory);$i++){
$rand = str_pad(dechex(rand(0, 0xFFFF00)), 6, 0, STR_PAD_LEFT);
echo('"#' . $rand.'"');
echo ",";
}
?>
],
label: 'Pie Chart'
}],
labels: [
<?php
for($i=0;$i<count($ageCategory);$i++){
echo $ageCategory[$i];
echo ',';
}
?>
],
},
options: {
responsive: true
}
};
$(function () {
var ctx1+q = document.getElementById('canvas'+q).getContext('2d');
window.myPie = new Chart(ctx1+q , canvas+q);
});
q=q+1;
But I am getting this error
Use of undefined constant k - assumed 'k' (this will throw an Error in a future version of PHP)
How do I fix it?
If you can use PHP variables in your JavaScript code, the contrary is not possible. The only way to pass JavaScript variable to PHP code is by request (reload page with GET/POST parameters or AJAX request)
I have two arrays in PHP which I am trying to pass to a Chart to be displayed in Chartjs.
The following code creates the arrays by using a foreach on a multidimensional array to extract them.
<?php
$behaviours = orderByType($_SESSION['loggedStudent']['studentID']);
$behTypes = array();
$behValues = array();
foreach($behaviours as $item){
$behTypes[] = $item["type"];
$behValues[] = intval($item["count(*)"]);
}
// php arrays to JSON
$behaviourLabels = json_encode($behTypes, TRUE);
$behaviourValues = json_encode($behValues, TRUE);
?>
<canvas id="pie-chart" width="800" height="450"></canvas>
<script>
// parse to js
var strLables = <?php echo($behaviourLabels); ?>;
var strValues = <?php echo($behaviourValues); ?>;
// parse as array
var arrLables = JSON.parse($strLables);
var arrValues = JSON.parse($strValues);
new Chart(document.getElementById("pie-chart"), {
type: 'pie',
data: {
labels: arrLabels,
datasets: [{
label: "Incident Type",
backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
data: arrValues,
}]
},
options: {
title: {
display: true,
text: 'Breakdown of incident types for <?php echo($_SESSION['loggedStudent']['firstName']); ?>'
}
}
});
</script>
No chart or labels are showing. What am I doing wrong?
The expected values for both data and labels are array.
What you need to do is pass json to JavaScript.
// php arrays to JSON
$behaviourLabels = json_encode($behTypes);
$behaviourValues = json_encode($behValues);
Now in javascript
var arrLables = <?php echo($behaviourLabels); ?>;
var arrValues = <?php echo($behaviourValues); ?>;
// Now use them directly in you configuration
data: {
labels: arrLables,
datasets: [{
label: "Incident Type",
backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
data: arrValues,
}]
},
I search for some code, even I found it, but I dunno how to add a new line of the javascript he creates.
The original link is this, I have some problem in code bellow. Because I have change the code "price": "120.00", to "price": "\\using php to call some data",.
This is original code:
{
"product_id": "1",
"store_id": "1",
"price": "120.00",
"sequence": "0",
"id": "1",
"parent_id": "0",
"name": "Store 1",
"email": "store1#store1.com"
}
This is what I wrote:
$result1=mysqli_query($conn, "select * from product");
while ($row1=mysqli_fetch_assoc($result1))
{
$pno1 = $row1["no"];
$sql1 = "SELECT * FROM xx where WHERE product_id = '$pno1') ";
$query1 = mysqli_query($conn , $sql1);
$rowcont1 = mysqli_num_rows($query1);
?>
{
"name": "<?php echo $row1["PACKAGE_NAME"]; ?>",
"id": "<?php echo $row1["PACKAGE_NAME"]; ?>",
"cat": "UNIFI",
<?php
if ($rowcont1 == 0)
{
?>
"vas": "<?php echo "No default vas"; ?>"
<?php
}
else
{
?>
"vas": "<?php
while($rowvas1=mysqli_fetch_assoc($query1))
{
echo "$rowvas1[PACKAGE_NAME]\\n\\n"; //This is the line I want to chage (\\n no function for me)
}
?>"
<?php
}
?>
},
<?php
I have found many question same with me, but even I have tried all of the solutions, my code still didn't work
Try the following instead:
echo "$rowvas1[PACKAGE_NAME]<br>";
Instead of \n just add html line-break <br>.
Edit: If you are using the JS provided in the jsfiddle, be sure to change the following line:
$('#price-store').text(pricestore[$('option:selected', this).index()].price);
to(.text( to .html():
$('#price-store').html(pricestore[$('option:selected', this).index()].price);
i want to show every row data from my table to highchart, how can i show that data using php to javascript foreach row?
<script>
series: [{
name: 'Mie Instan',
data: [<?php foreach ($query as $row){echo $row['mie'];}]
}, {
name: 'Beras',
data: [<?php foreach ($query as $row){echo $row['beras'];}]
}, {
name: 'Telur',
data: [<?php foreach ($query as $row){echo $row['telur'];}]
}]
</script>
What I would do, in order to get the HighCharts data arranged as an array of numerical values, is to use php array_push and PHP foreach to sort the data in three different PHP arrays.
<?php
// Declare 3 new arrays.
$mie=[];
$beras=[];
$telur=[];
// Fill the arrays with the database values
foreach ($query as $row){
array_push($mie, $row['mie']);
array_push($beras, $row['beras']);
array_push($telur, $row['telur']);
}
?>
Then use the arrays to produce a string of "coma separated values" in the HighCharts script, using PHP join, like this:
<script>
series: [{
name: 'Mie Instan',
data: [<?php echo join(",", $mie); ?>]
}, {
name: 'Beras',
data: [<?php echo join(",", $beras); ?>]
}, {
name: 'Telur',
data: [<?php echo join(",", $telur); ?>]
}]
</script>
Hoping this helps...
;)
Script I'm using:
if(isset($_GET['cap']) && isset($captions[$_GET['cap']])){
$cap = $captions[$_GET['cap']];
}
if(isset($cap)){
}
How can I insert the $cap inside a JavaScript parameter?
Example:
tracks: [{
file: 'http://mylink.com/caption.srt',
label: 'English',
kind: 'captions',
'default': true
}],
Do like this:
<?php
if(isset($_GET['cap']) && isset($captions[$_GET['cap']])){
$cap = $captions[$_GET['cap']];
?>
<script>
tracks: [{
file:<?php echo $cap; ?>,
label: 'English',
kind: 'captions',
'default': true
}],
</script>
<?php
}
?>
You can combine JS and PHP, by keeping JS inside a PHP if statement, it shall work as you expect
OR
You may try this:
<?php
if(isset($_GET['cap']) && isset($captions[$_GET['cap']])){
$cap = $captions[$_GET['cap']];
echo"<script>tracks:file:".$cap.",label: 'English',kind: 'captions','default':true}],</script>"
}
?>
This would assign the value into file
tracks: [{
file: '<b><?= $cap ?></b>',
label: 'English',
kind: 'captions',
'default': true
}],
In your script
<script>
var cap = '<?php echo $cap; ?>'
tracks: [{
file:cap,
label: 'English',
kind: 'captions',
'default': true
}],
</script>
Now cap is can be use in your scripts.