I am trying to pass some formatted String from PHP to jQuery. But i am getting an error as
VM2203:3 Uncaught SyntaxError: Unexpected number in the browser.
Here is my code
<?php
$OSlist = [];
$category = "";
$pieData = "";
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_PORT => "8081",
CURLOPT_URL => "http://localhost:8081/api/devices/hoursBy/OSVersion",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
$decodeStr = json_decode($response, true);
foreach ($decodeStr as $item) {
$os = $item['_id']['os'];
if ($os == $selectedOS) {
if ($item['total_hours'] != 0) {
$OSlist[$item['_id']['version']] = $item['total_hours'];
// echo 'iOS'.$item['_id']['version'] . ' : ' . $item['total_hours'] ,"<br>";
}
}
}
ksort($OSlist);
foreach ($OSlist as $key => $val) {
// echo "$key = $val" . "<br>";
$category = $category . $key . ",";
$pieData = $pieData . "[" . $key . "," . $val . "],";
}
$pieData="[".$pieData."]";
echo $pieData;
// print_r($OSlist);
} ?>
<script >
$('document').ready(function () {
var jsArray = <?php echo $pieData; ?>;
alert(jsArray);
});
</script>
The Piedata output is
[[2.3.4,97.9],[4.0.3,11.6],[4.0.4,2.4],[4.1.1,15.1],[4.1.2,398.4],[4.2.1,45.8],[4.2.2,27.3],[4.3,321],[4.4.2,694.9],[4.4.4,478.7],[5,646.3],[5.0.1,177.5],[5.0.2,1210.5],[5.1,126.2],[5.1.1,524.4],[6,201.5],]
i actually need to pass this data to highchart pie graph to the data value.The following graph is for mobile version vs its utilization hours.
function loadPieGraph() {
// Radialize the colors
var android = <?php echo $androidhrs ?>;
var ios = <?php echo $ioshrs ?>;
var obj = [{
type: 'pie',
name: 'Browser share',
data: [
['4.1', '23.0'],
{
name: '5.0',
y: '40.2',
sliced: true,
selected: true
},
]
}];
Highcharts.getOptions().colors = Highcharts.map(Highcharts.getOptions().colors, function (color) {
return {
radialGradient: {
cx: 0.5,
cy: 0.3,
r: 0.7
},
stops: [
[0, color],
[1, Highcharts.Color(color).brighten(-0.3).get('rgb')] // darken
]
};
});
// Build the chart
$('#container').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: 'Browser market shares. January, 2015 to May, 2015'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
},
connectorColor: 'silver'
}
}
},
series: obj
});
}
This whole part:
foreach ($OSlist as $key => $val) {
// echo "$key = $val" . "<br>";
$category = $category . $key . ",";
$pieData = $pieData . "[" . $key . "," . $val . "],";
}
$pieData="[".$pieData."]";
echo $pieData;
// print_r($OSlist);
} ?>
<script >
$('document').ready(function () {
var jsArray = <?php echo $pieData; ?>;
alert(jsArray);
});
</script>
looks really faulty in nature.
You should rather:
$pieData = json_encode($OSlist);
and in the script tag you can simply do this:
jsArray = JSON.parse("<?php echo $pieData; ?>");
And then do the HighChart's relevant array formatting in the JS.
Or you can directly do the formatting first in PHP and do json encode the final form and directly pass it to js where again you will need to JSON.parse them again.
Always do data transactions in form of JSON in these types of cases.
Hope it helps.
Hope it helps.
Related
I'm new in Apexcharts, and I try to make a pie chart with data, getting from mysql database. This is the php-file named "get_types_chart.php"
$year = date('Y');
$month = date('m');
$graf = PDO()->prepare("SELECT COUNT(tickets.id) AS cid, types.ticket_type AS type_name FROM tickets LEFT JOIN types ON tickets.type=types.id WHERE tickets.arch=0 AND tickets.status NOT IN (2, 4) AND MONTH(tickets.date_create)=:month AND YEAR(tickets.date_create)=:year GROUP BY types.ticket_type");
$graf->execute([':year' => $year,
':month' => $month]);
$arrData = array();
while($row = $graf->fetch(PDO::FETCH_LAZY)) {
array_push($arrData, array(
"labels" => $row->type_name,
"series" => $row->cid
)
);
}
$jsonEncodedData = json_encode($arrData);
header('Content-Type: application/json');
echo $jsonEncodedData;
And this is the js-code:
var url3 = 'charts/get_types_chart.php';
var options3 = {
series: [],
chart: {
width: 380,
type: 'pie',
},
title: {
text: '<?php echo lang('MON_STAT_year'); ?>',
floating: true,
align: 'center'
},
labels: [],
responsive: [{
breakpoint: 480,
options: {
chart: {
width: 200
},
legend: {
position: 'bottom'
}
}
}]
};
var chart3 = new ApexCharts(document.querySelector("#chart3"), options3);
chart3.render();
$.getJSON(url3, function(response) {
chart3.updateSeries([{
name: '<?php echo lang('DASH_STAT_month_all'); ?>',
data: response
}])
});
Finally I get empty pie. Please hel me to make a correct json.
I have a task to solve how to change JSON encode to array string,
look at my code below: I have
["11:00"]["09:00"]["01:00"]["12:00"]["11:00"]["10:00"]["01:00"]["00:00"]["23:00"]["22:00"]
how to change it to become
["11:00","09:00","01:00","11:00","10:00","01:00","00:00","23:00","22:00"]
My stats.php looks like this:
out .= ' <div class="col-lg-5 col-md-5 col-sm-5 col-lg-offset-1 col-md-offset-1 col-sm-offset-1" style="height: 300px">';
$out .= ' <div class="chartjs-size-monitor">';
$out .= ' <div class="chartjs-size-monitor-expand">';
$out .= ' <div class=""></div>';
$out .= ' </div>';
$out .= ' <div class="chartjs-size-monitor-shrink">';
$out .= ' <div class=""></div>';
$out .= ' </div>';
$out .= ' </div>';
$out .= ' <canvas id="myChart2" class="canpas chartjs-render-monitor" style="display: block; width: 454px; height: 300px;" width="454" height="300"></canvas>';
$out .= ' </div>';
$graph_query = mssql_query("SELECT TOP 100 Convert(nvarchar,dtDate,108) AS Date, serial, nAverageUser, nMaxUser FROM tbl_ServerUser_Log ORDER BY serial DESC");
$i = 1;
while ($graph = mssql_fetch_array($graph_query)) {
$graph['nMaxUser'] = round($graph['nMaxUser'] * $percent_inc);
$graph['nAverageUser'] = round($graph['nAverageUser'] * $percent_inc);
$serie1->addPoint(new Point($graph['Date'], $graph['nMaxUser']));
$serie2->addPoint(new Point($graph['Date'], $graph['nAverageUser']));
$date = date('H:i', strtotime($graph['Date']));
$convert = json_encode(str_split($date, 5));
// $convert = str_replace('][','',$convert);
echo $convert;
}
I want to show a chart and send the value in HTML.
The HTML shall look like this:
<script type="text/javascript">
var ctx = document.getElementById('myChart2').getContext('2d');
var myChart2 = new Chart(ctx, {
type: 'line',
data: {
labels: ['00:00','01:00','02:00','03:00','04:00','05:00','06:00','07:00','08:00','09:00','10:00','11:00','12:00','13:00','14:00','15:00','16:00','17:00','18:00','19:00','20:00','21:00','22:00','23:00'], //Jamnya
datasets: [{
backgroundColor: 'rgba(232,72,163,0.2)',
borderColor: '#e848a3',
label: '29 May 2020',
data: [807,657,600,578,565,576,611,855,625,573,571,584,607,647,771,943,920,647,622,608,722,832,902,1062],
fill: true,
pointRadius: 5,
pointHoverRadius: 10,
showLine: true
}]
}, options: {
responsive: true,
maintainAspectRatio: false,
title: {
display: true,
text: 'Total Online Yesterday',
position: 'top',
fontSize: 15,
fontStyle: 'bold'
},
legend: {
display: false
},
elements: {
point: {
pointStyle: 'circle'
}
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'TIME'
},
ticks: {
major: {
fontStyle: 'bold',
fontColor: '#FF0000'
}
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'TOTAL ONLINE'
}
}]
},
tooltips:{
callbacks: {
title: function(tooltipItem, data) {
return '29 May 2020 '+data['labels'][tooltipItem[0]['index']];
},
label: function(tooltipItem, data) {
return 'TOTAL : '+data['datasets'][0]['data'][tooltipItem['index']]+'';
},
},
titleFontSize: 15,
bodyFontSize: 15,
displayColors: false
}
}
});
</script>
I just want to show my chart from manual value to query value that I catch from an SQL server.
Thanks in advance for answering my question.
Don't echo JSON every time through the loop. Put the times in a single array, and echo the JSON at the end.
$dates = [];
while ($graph = mssql_fetch_array($graph_query)) {
$graph['nMaxUser'] = round($graph['nMaxUser'] * $percent_inc);
$graph['nAverageUser'] = round($graph['nAverageUser'] * $percent_inc);
$serie1->addPoint(new Point($graph['Date'], $graph['nMaxUser']));
$serie2->addPoint(new Point($graph['Date'], $graph['nAverageUser']));
$date = date('H:i', strtotime($graph['Date']));
$dates[] = $date;
echo $convert;
}
echo json_encode($dates);
I have a problem with an php app that sends a test result. It should load an image filled with some css, but it doesn't, it tries to load the image, but it doesn't work. It used to work. IDK what happened.
So the app should return something like this:
exemple
from this image
Original image
Is the problem in the code below?
Any help please?
foreach($charts as $id=>$chart){
?>
<script>
jQuery( document ).ready(function() {
var isSaved<?php echo $chart['name']; ?>=false;
var isImageLoad<?php echo $chart['name']; ?> = false;
var imageObj = new Image();
imageObj.src = '<?php echo get_site_url(); ?>/wp-content/themes/coaching/roata_vietii/roata2.png';
var <?php echo $chart['name']; ?> = document.getElementById("<?php echo $chart['name']; ?>");
var <?php echo $chart['name']; ?>Data = {
labels: [<?php echo $labels; ?>],
padding: {
bottom: 900
},
datasets: [{
borderWidth: 0,
data: [<?php echo ${$chart['variabila']}; ?>],
backgroundColor: [<?php echo $backgroundColor; ?> ]
}]
};
var polarAreaChart = new Chart(<?php echo $chart['name']; ?>, {
type: 'polarArea',
data: <?php echo $chart['name']; ?>Data,
responsive:false,
options: {
events: [],
layout: {
padding: {
left:70,
right:70,
//top:10,
//bottom:10
},
},
legend: {
display:false,
/* labels: {
padding:20,
boxWidth:20,
fontSize:15
},*/
},
scale: {
ticks: {
min: 0,
max: 10,
display:false,
},
},
hover: {
animationDuration: 0
},
animation: {
duration: 0,
onComplete: function() {
var chartInstance = this.chart;
var ctx = chartInstance.ctx;
var datasets = this.data.datasets;
imageObj.onload = function() {
if(isSaved<?php echo $chart['name']; ?> == false){
ctx.drawImage(imageObj, 0, 0);
/* ctx.font = "bolder 15px Arial";
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
ctx.fillStyle = "grey";
datasets.forEach(function(dataset, i) {
var meta = chartInstance.controller.getDatasetMeta(i);
meta.data.forEach(function(bar, index) {
var myangl=((bar._model.startAngle)+(bar._model.endAngle))/2;
// var xpoint= (parseFloat(bar._model.outerRadius)+20)*(Math.cos(myangl)) + (bar._model.x);
// var ypoint= (parseFloat(bar._model.outerRadius)+20)*(Math.sin(myangl)) + (bar._model.y);
var xpoint= (parseFloat(370)+20)*(Math.cos(myangl)) + (bar._model.x);
var ypoint= (parseFloat(370)+20)*(Math.sin(myangl)) + (bar._model.y);
ctx.fillText(bar._model.label,xpoint ,ypoint);
});
});*/
isSaved<?php echo $chart['name']; ?> = true;
jQuery.ajax({
url: '<?php echo get_site_url(); ?>/wp-content/themes/coaching/roata_vietii/roataVietii-saver.php',
type: 'POST',
data: {
"image" : <?php echo $chart['name']; ?>.toDataURL("image/<?php echo $chart['extension']; ?>"),
"name" : "<?php echo $chart['name_of_file']; ?>" + ".<?php echo $chart['extension']; ?>",
"save_location" : "<?php echo $chart['save_location']; ?>" ,
},
success: function ()
{
<?php /*if($id !== 1 ){ ?>
//if the image is saved, resize the canvas to 100%, for the user
setTimeout(function () {
var tmpCC = document.getElementById("chart-container<?php echo $chart['name']; ?>");
tmpCC.style.backgroundImage = 'url("<?php echo get_site_url(); ?>/wp-content/themes/coaching/roata_vietii/images/<?php echo $chart['name_of_file'].".".$chart['extension'];?>")';
tmpCC.style.width = "100%";
tmpCC.style.height = tmpCC.offsetWidth+"px";
},500);
<?php } */ ?>
},
});
}
}
}
}
}
});
});
</script>
i want to load some data from an sql-table and use them with jquery to color a map.
I picked up the data with PHP:
<?php
include 'connect.php';
session_start();
$userid = $_SESSION['userid'];
$sql = "
SELECT landstatus.shortland
FROM landstatus
WHERE users_id='1'
AND status ='wanttovisit'
";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["shortland"]. "<br>";
}
}
$conn->close();
?>
Now i want to use shortland for the static value 'ca' in jquery:
<script>
jQuery(document).ready(function () {
jQuery('#vmap').vectorMap({
map: 'world_en',
backgroundColor: '#333333',
color: '#FFFFFF',
hoverOpacity: 0.7,
selectedColor: '#727272',
enableZoom: true,
colors:{
'ca' : '#4E7387',
},
series: {
regions:
[{
attribute: 'fill'
}]
},
onRegionClick: function (element, code, region) {
$(".info-box-region").append(region);
$(".info-box").show();
$("input[name=region]").val(region);
$('input[name=code]').val(code);
}
});
});
</script>
At the end colors would be filled with all shortlands from the database - each shortland has the same hex-code.
Thx for helping me.
Place all shortland values in an array and loop through it to create the ca entries
$result = $conn->query($sql);
$shortlands = array();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$shortlands[] = $row["shortland"];
}
}
Then loop over the values. e.g.
colors:{
<?php
foreach ($shortlands as $val) {
echo "'{$val}': '#4E7387',\n";
}
?>
},
You can "pass" anything PHP knows into JavaScript variables simply by echoing them into JavaScript code in your template:
<script>
var myJavaScriptVar = <?php echo $myPhpVar ?>
</script>
Just do this:
<script>
jQuery(document).ready(function () {
jQuery('#vmap').vectorMap({
map: 'world_en',
backgroundColor: '#333333',
color: '#FFFFFF',
hoverOpacity: 0.7,
selectedColor: '#727272',
enableZoom: true,
colors:{
'ca' : '<?php echo $row["shortland"] ;?>',
},
series: {
regions:
[{
attribute: 'fill'
}]
},
onRegionClick: function (element, code, region) {
$(".info-box-region").append(region);
$(".info-box").show();
$("input[name=region]").val(region);
$('input[name=code]').val(code);
}
});
});
</script>
I am working with Dygraphs to chart Arduino sensor data.I need to get a subtract between two data so i am using php inside a script function but it doesn't work.It is possible to include
<script type="text/javascript">
var csv = [
'<?php
$row = 1;
if (($handle = fopen("https://api.thingspeak.com/channels/***/feed.csv?key=***&start=<?php echo $_POST['day_ini'];?>%20<?php echo $_POST['hour_ini'];?>&end=<?php echo $_POST['day_end'];?>%20<?php echo $_POST['hour_end'];?>", "r")) !== FALSE) {
...
?>','2015-11-02 20:54:50 UTC,1049703,5,5'
];
This is all my function code:
<script type="text/javascript">
var csv = [
'<?php
$row = 1;
if (($handle = fopen("https://api.thingspeak.com/channels/***/feed.csv?key=***&start=2015-11-02%2020:50:45&end=2015-11-02%2021:50:45", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 50, ",")) !== FALSE) {
if($row == 1){ $row++; continue; }
$num = count($data);
for ($c=0; $c < $num; $c++) {
if(strpos($data[$c], 'Finished') !== false) {
$c++;
echo $data[$c] . "," ; }
Else{
echo $data[$c] . "," ;
}
}
}
fclose($handle);
}
?>','2015-11-02 20:54:50 UTC,1049703,5,5'
//... etcetera
];
function getPairDifference(pair) {
//"pair" is a zero-based integer.
// "0" will return a difference between csv rows "0" & "1"
// "1" will return a difference between csv rows "1" & "2"
// etcetera...
var firstVal = parseInt(csv[pair].split(",")[3]);
var secondVal = parseInt(csv[pair + 1].split(",")[3]);
return firstVal - secondVal;
}
for (var i = 0; i < csv.length; i += 1) {
// Demo code to visualize numbers.
// Actual function call of interest is simply "getPairDifference( i )"
var plot = getPairDifference(i);
// $("<div></div>").text(plot).appendTo("body");
$(function() {
$("#chart3").chart({
template: "line_basic_6",
tooltips: {
serie1: [plot],
width:20,
height:15,
},
values: {
serie1: [plot]
},
labels: ["Period 1","Period 2"],
defaultSeries: {
type: "bar",
stacked: true
},
series: {
serie3: {
type: "line",
stacked: false,
axis: "r"
}
},
axis: {
r: {
max: 100,
suffix: "%"
}
}
});
});
$.elycharts.templates['line_basic_6'] = {
type: "line",
margins: [10, 40, 40, 30],
defaultSeries: {
highlight: {
newProps: {
r: 8,
opacity: 1
},
overlayProps: {
fill: "white",
opacity: 0.2
}
}
},
series: {
serie1: {
color: "90-#003000-#009000",
tooltip: {
frameProps: {
stroke: "green"
}
}
},
},
defaultAxis: {
labels: true
},
axis: {
x: {
labelsRotate: 0,
labelsProps: {
font: "11px Verdana"
}
}
},
features: {
grid: {
draw: true,
forceBorder: true,
ny: 5
}
},
barMargins: 180
};
}
</script>
Thanks in advance.
no need to echo like that and you are using <?php inside another <?php before closing that.
<script type="text/javascript">
var csv = [
'<?php
$row = 1;
if (($handle = fopen("https://api.thingspeak.com/channels/***/feed.csv?key=***&start={$_POST['day_ini']}%20{$_POST['hour_ini']}&end={$_POST['day_end']}%20{$_POST['hour_end']}", "r")) !== FALSE) {
}
?>', '2015-11-02 20:54:50 UTC,1049703,5,5'
];
</script>
And i am not sure of }, please check that once.
You have missunderstood something about PHP and Javascript.
Javascript gets sended to the Client, so it works in the Browser and also get's executed.
PHP altough gets executed on the Server first, there lies your problem, you can't execute on the Client something that needs to be done by a Server.