Integrate PHP variables in Javascript [duplicate] - javascript

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 2 years ago.
I have this Javascript which outputs a chart with some values:
<script type="text/javascript">
//pie
var ctxP = document.getElementById("pieChart").getContext('2d');
var myPieChart = new Chart(ctxP, {
type: 'pie',
data: {
labels: ["Red", "Blue"],
datasets: [{
data: [10, 90],
backgroundColor: ["#F7464A", "#46BFBD"],
hoverBackgroundColor: ["#FF5A5E", "#5AD3D1"]
}]
},
options: {
responsive: true
}
});
</script>
I need to customize some values, as the ones in labels or data, coming from some calculations previously made in PHP.
What I tried so far was unsuccessfull, probably because I am missing something.
To simplify what I did, here the code:
//PHP code where I define some variables as strings
<?php
$color1 = "Black";
$color2 = "White";
?>
//Then comes again the Javascript code:
<script type="text/javascript">
//pie
var ctxP = document.getElementById("pieChart").getContext('2d');
var myPieChart = new Chart(ctxP, {
type: 'pie',
data: {
labels: [<?php echo $color1, $color2; ?>], //////////Here my modification
datasets: [{
data: [10, 90],
backgroundColor: ["#F7464A", "#46BFBD"],
hoverBackgroundColor: ["#FF5A5E", "#5AD3D1"]
}]
},
options: {
responsive: true
}
});
</script>
This does not work, but I do not understand why.
I also tried with:
<?php
$colors = array("Black", "White");
?>
passing the $colors variable, but nothing changes.
What kind of mistake am I making?
How can I fix this?

In a php file it can be done with json_encode
<?php
// your php code
?>
<script>
var jsObject = <?php
echo json_encode([
'my_variable1' => 'value1',
'my_variable2' => 'value2'
]);
?>
console.log(jsObject);
</script>

Related

PHP not showing within the data part of a chart.js

I have managed to get both PHP and JavaScript code working on the same page. In the top of the page on the left you can see that my figures from my php tables are being pulled out correctly however, the moment I go to paste the php code inside of where the table 'data' needs to be kept it doesn't work even though surrounded in php tags.
<?php
$conn = mysqli_connect("localhost", "x", "y", "z");
$query = "SELECT * FROM `checkPointMod`";
$result = $conn -> query($query);
while($row = $result -> fetch_assoc())
{
echo $row['mod1']."<br>";
echo $row['mod2']."<br>";
echo $row['mod3']."<br>";
echo $row['mod4']."<br>";
echo $row['mod5']."<br>";
echo $row['mod6']."<br>";
}
$conn -> close();
?>
<!DOCTYPE html>
<html lang="en-GB">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>
</head>
<body style="background-color: lightgrey;">
<div class="col-md-4 text-center">Third of Page - Middle section with progress bar
<canvas id="myChart" width="400" height="400"></canvas>
</div>
<script type="text/javascript">
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [<?php echo $row['mod1']?>, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
</script>
</html>
Update: - I've gone to inspect element to see what the output is and it's seen here, I also placed mod2 in to see if 6 would appear...
I missed that $row only exists inside that while loop.
Replace your while loop with this:
$rows = [];
while ($row = $result -> fetch_assoc()) $rows[] = $row;
Down in your Javascript code, add this at the top:
const data = <?= json_encode($rows, JSON_NUMERIC_CHECK) ?>;
You should end up with this in your page source:
const data = [{ "checkPID": 6, "mod1": 0, "mod2": 6, "mod3": 0, "mod4": 3, "mod5": 2, "mod6": 1, "idUsers": 1 }];
Now you can do this in your Chart setup:
data: Object.keys(data[0]).filter(key => key.startsWith("mod")).map(key => data[0][key]),

parse array in charts js laravel blade

I need show temperature monthly to charts in laravel
my view page consist
temp.blade
<script>
console.log({!! $temp !!});
console.log({!! $dateTemp !!});
window.onload = function() {
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: {!! $temp !!},
datasets: [{
label: 'Temperature',
data: {!! $dateTemp !!},
borderWidth: 1
}]
}
});
}
</script>
and controller
public function tempChart()
{
$temp = Temps::select(DB::raw('temp'))
->orderBy('date_temp','asc')
->get();
$temp->implode(',',$temp);
$dateTemp = Temps::select(DB::raw('temps'))
->select('date_temp')
->orderBy('date_temp','asc')
->get();
$dateTemp->implode(',',$dateTemp);
//dd($temp,$dateTemp);
return view('report/temp')
->with('temp',$temp)
->with('dateTemp',$dateTemp);
}
it can not show data array but it show
[{...}],[{...}],[{...}]
I am not sure which Chart library you are using but most of them wants an array of strings or integer and you give them array of objects.
I think that you just need to convert your array in the php (or in the javescript)
php way:
$temp = Temps::select('temp'`)
->orderBy('date_temp','asc')
->get()
->pluck('temp');
$dateTemp = Temps::select(['temps', 'data-temp'])
->orderBy('date_temp','asc')
->get()
->pluck('data-temp'); // I am not whats the acual query you want but this is the idea
and then if you using laravel 5.5 just write on your blade
<script>
window.onload = function() {
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: #json($temp),
datasets: [{
label: 'Temperature',
data: #json($dateTemp) ,
borderWidth: 1
}]
}
});
}
</script>
Try add high comma to Data?
datasets: [{
label: 'Temperature',
data: '{!! $dateTemp !!}',
borderWidth: 1
}]

Chart.js; Chart is not showing time and imported data.

I am quite new to programming and expecially javascript.
To learn javascript I was thinking to create a chart using "ticker data" from coinmarketcap. To get the ticker data I created the following function:
function golemPrice() {
//Fetch data
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://api.coinmarketcap.com/v1/ticker/golem-network-tokens/?convert=EUR");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$rawData = curl_exec($curl);
curl_close($curl);
// decode to array
$data = json_decode($rawData);
//Access array[0] and select value price_eur
$gntPrice = $data[0]->price_eur;
// show data
return $gntPrice;
}
?>
To put the data into a chart, I was thinking to use chart.js. I created the following chart:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.js"></script>
<script>
let priceFromFunction = ["<?php golemPrice();?>"];
let timeFormat = "MM/DD/YYYY HH:mm";
let myChart = document.getElementById('golemChart').getContext('2d');
let lineChart = new Chart(myChart, {
type: 'line',
data: {
datasets: [{
label: 'Golem chart',
borderColor: "rgba(80, 164, 245, 4)",
data: priceFromFunction
}]
},
options: {
scales: {
xAxes: [{
type: "time",
time: {
format: timeFormat,
// round: 'day'
tooltipFormat: 'll HH:mm'
},
scaleLabel: {
display: true,
labelString: 'Date'
}
}, ],
yAxes: [{
scaleLabel: {
display: true,
labelString: 'Price'
}
}]
},
}
});
</script>
Unfortunately my chart is not showing the date and no data from the function is added. I tried many different things but now I am out of ideas.
Hopefully you can help me.
You are missing echo the function value, try replace this:
let priceFromFunction = ["<?php golemPrice();?>"];
to
let priceFromFunction = ["<?php echo golemPrice() ?>"];

c3.js TypeError: b.value is undefined

I am trying to make a graph using a JSON object created in my PHP. I keep getting TypeError: b.value is undefined in the JS log but my data seems to be in the same format as the example in their documentation.
for($i = 0; $i < 10; $i++){
$da=date("Y-m-d", strtotime('-'. $i .' days'));
$a=mt_rand(150,200);
$b=mt_rand(100,150);
$ar["date"][]=$da;
$ar["Score"][]=$a;
$ar["ScoreB"][]=$b;
}
$all=json_encode($ar);
<script>
var arr=<?php echo $all; ?>;
var chart = c3.generate({
bindto: '#scoring',
data: {
json: arr,
type: 'spline',
keys:{
x:'date'
}
},
color: {
pattern: ['red', 'orange']
},
axis: {
x: {
type: 'timeseries',
tick: {
format: '%Y-%m-%d'
}
}
}
});
The Object is
{"date":"2016-05-09","2016-05-08","2016-05-07","2016-05-06","2016-05-05","2016-05-04","2016-05-03","2016-05-02","2016-05-01","2016-04-30"],"Score":[182,163,196,153,180,154,170,177,191,173],"ScoreB":[121,149,138,113,104,107,111,109,119,132]}
I also ran it with the object in the format of
[{"date":"2016-05-09","Score":191,"ScoreB":119},{"date":"2016-05-08","Score":166,"ScoreB":140},{"date":"2016-05-07","Score":172,"ScoreB":103},{"date":"2016-05-06","Score":187,"ScoreB":139},{"date":"2016-05-05","Score":162,"ScoreB":100},{"date":"2016-05-04","Score":197,"ScoreB":121},{"date":"2016-05-03","Score":167,"ScoreB":145},{"date":"2016-05-02","Score":160,"ScoreB":137},{"date":"2016-05-01","Score":175,"ScoreB":100},{"date":"2016-04-30","Score":156,"ScoreB":127}]
And I still have the same error.
I have been stuck on this for a day and it seems like it should be easy but I can not figure it out. If I put the same data in the format of "columns" it works but going forward I need this JSON to work.
This works for me when cut'n'pasted into http://c3js.org/samples/timeseries.html , see the change in the keys section with the added value field - http://c3js.org/reference.html#data-keys
The only difference is that I changed the binding ID to work in the c3 examples page, and I used the json directly, not php generated.
var arr = [{"date":"2016-05-09","Score":191,"ScoreB":119},{"date":"2016-05-08","Score":166,"ScoreB":140},{"date":"2016-05-07","Score":172,"ScoreB":103},{"date":"2016-05-06","Score":187,"ScoreB":139},{"date":"2016-05-05","Score":162,"ScoreB":100},{"date":"2016-05-04","Score":197,"ScoreB":121},{"date":"2016-05-03","Score":167,"ScoreB":145},{"date":"2016-05-02","Score":160,"ScoreB":137},{"date":"2016-05-01","Score":175,"ScoreB":100},{"date":"2016-04-30","Score":156,"ScoreB":127}]; ;
var chart = c3.generate({
bindto: '#chart',
data: {
json: arr,
type: 'spline',
keys:{
x:'date',
value: ['Score', 'ScoreB'], // IMPORTANT
}
},
color: {
pattern: ['red', 'orange']
},
axis: {
x: {
type: 'timeseries',
tick: {
format: '%Y-%m-%d'
}
}
}
});

Graphing Data with jQuery Flot from a MySQL database

I am trying to have a graph display registration data generated from the mysql database. The format for data seems to be coming out correctly but the data is not being plotted. Please note that I am using CodeIgniter.
PHP:
public function graph_registrations()
{
$send = array();
$i = 1;
while($i <= 30){
$startTime = mktime(0, 0, 0, date('m'), date('d')-$i, date('Y'));
$endTime = mktime(23, 59, 59, date('m'), date('d')-$i, date('Y'));
$data = $this->admin_model->total_users_date($startTime, $endTime);
$new = array(date("M j", $startTime), $data);
$send[] = $new;
$i++;
}
echo json_encode($send);
}
JS:
var jsonData = $.ajax({
url: default_url+"admin/graph_registrations",
dataType:"json",
async: false
}).responseText;
console.log(jsonData);
var graphData = [{
// Visits
data: jsonData,
color: '#71c73e',
points: { radius: 4, fillColor: '#71c73e' }
}
];
// Lines
$.plot($('#graph-lines'), graphData, {
series: {
points: {
show: true,
radius: 5
},
lines: {
show: true
},
shadowSize: 0
},
grid: {
color: '#646464',
borderColor: 'transparent',
borderWidth: 20,
hoverable: true
},
xaxis: {
tickColor: 'transparent',
tickDecimals: 2
},
yaxis: {
tickSize: 1000
}
});
Everything works if I manually hard code the data in, but not when I grab it via ajax.
This is what console.log(jsonData) produces:
[["Dec 5",0],["Dec 4",0],["Dec 3",0],["Dec 2",0],["Dec 1",0],["Nov 30",0],["Nov 29",0],["Nov 28",0],["Nov 27",0],["Nov 26",0],["Nov 25",0],["Nov 24",0],["Nov 23",0],["Nov 22",0],["Nov 21",0],["Nov 20",0],["Nov 19",0],["Nov 18",0],["Nov 17",0],["Nov 16",0],["Nov 15",0],["Nov 14",0],["Nov 13",0],["Nov 12",0],["Nov 11",0],["Nov 10",0],["Nov 9",1],["Nov 8",0],["Nov 7",0],["Nov 6",0]]
I tried doing it without the date and just a plain number, but it did not work.
Thank you
For me you are trying to plot the data before having them. I can see you are using "async:false" to wait for the data to be loaded by I'd rather used the default "true" option and placed the plotting function in "success" callback of $.ajax.

Categories

Resources