Why the php code doesn't write the image? - javascript

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>

Related

How to make a correct json to provide data to Apexcharts pie?

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.

CanvasJS in function only shows one chart (php, js)

function timeDataToPointChart($dataPoints,$title,$xlabel,$ylabel,$chartID) {
?>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script>
window.onload = function () {
var NameOfChart = "<?php echo $chartID; ?>"
window[NameOfChart] = new CanvasJS.Chart("chartContainer",
{
animationEnabled: true,
title:{
text: "<?php echo $title; ?>"
},
axisX:{
title: "<?php echo $xlabel; ?>",
valueFormatString: "MM/YYYY",
crosshair: {
enabled: true
}
},
axisY: {
title: "<?php echo $ylabel; ?>"
},
data: [
{
type: "line",
xValueType: "dateTime",
dataPoints:
<?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
}
]
});
window[NameOfChart].render();
function toggleDataSeries(e){
if (typeof(e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
e.dataSeries.visible = false;
}
else{
e.dataSeries.visible = true;
}
window[NameOfChart].render();
}
}
</script>
<div id="chartContainer" style="height: 370px; width: 650px;"></div>
<?php
}
?>
I use this PHP function to generate my canvas chart. This works well, but if I call the function twice on a page, only one chart is shown.
Console shows the following error, but I don't understand what's wrong.
CanvasJS namespace already exists. If you are loading both chart and
stockchart scripts, just load stockchart alone as it includes all
chart features.
Thank you for your help.
As described from canvasJs, i've implemented the code accordingly in my Laravel App like below
#foreach($records as $record)
<div id="chartContainer{{$record->employeeRequisitionId}}" style="height: 270px; width: 100%;"></div>
#endforeach
#push('after_scripts')
<script>
window.onload = function () {
#foreach($records as $record)
const chart{{$record->employeeRequisitionId}} = new CanvasJS.Chart ( "chartContainer{{$record->employeeRequisitionId}}", {
animationEnabled: true,
theme: "light2",
title: {
text: "Requisition According Fiscal Year"
},
axisY: {
suffix: "%",
scaleBreaks: {
autoCalculate: false
}
},
data: [{
type: "column",
yValueFormatString: "#,##0\"%\"",
indexLabel: "{y}",
indexLabelPlacement: "inside",
indexLabelFontColor: "white",
dataPoints: {!! formatRequisitionAccordingFiscalYearData($record) !!}
}]
} );
#endforeach
#foreach($records as $record)
chart{{$record->employeeRequisitionId}}.render ();
#endforeach
}
</script>
#endpush

Chart.js add icons like <i class='icon-peso'></i> to y-axis labels

I have these currency classes for <i> </i> tags e.g. ".icon-peso".
How do I format the y-axis in chart.js to show these <i class="icon-peso"> </i> tags?
Also these classes use a custom font that I've uploaded into http://app.fontastic.me/
What I need is to show it like this: P100,00.00.
Here's my code:
$(document).ready(function(){
var barLabel = <?php echo json_encode($ch3_arrDate); ?>;
var dataVal1 = <?php echo json_encode($ch3_arrRevenue_conf); ?>;
var dataVal2 = <?php echo json_encode($ch3_arrRevenue_tent); ?>;
var dateFilter = <?php echo json_encode($ch3_arrDate2); ?>;
var barData = {
labels: barLabel,
datasets: [
{
label: 'Confirmed Revenue',
backgroundColor: 'rgba(163,216,3,0.5)',
data: dataVal1,
},
{
label: 'Tentative Revenue',
backgroundColor: 'rgba(28,83,130,0.5)',
data: dataVal2,
},
]
};
var barOptions = {
responsive: true,
maintainAspectRatio: true,
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
userCallback: function(value, index, values) {
return addCommas(value.toFixed(2));
}
}
}]
},
legend: {
display: true,
position: 'bottom'
},
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
return addCommas(tooltipItem.yLabel.toFixed(2));
}
}
}
}
var ctx = document.getElementById("chart3").getContext("2d");
ctx.canvas.height = 300;
var chartDisplay = new Chart(ctx, {
type: 'line',
data: barData,
options: barOptions
});
$("#chart3").click(
function(e){
var activeBars = chartDisplay.getElementsAtEvent(e);
var index = activeBars[0]["_index"];
location.href="dash_chartdeals.php?from=future&filter_date="+fixedEncodeURIComponent(dateFilter[index]);
});
$("#chart3").mouseenter(function(){
$("#chart3").css("cursor", "pointer");
});
});
Update your exist variables with below and try.
var barLabel = '<?php echo json_encode($ch3_arrDate) ?>';
var dataVal1 = '<?php echo json_encode($ch3_arrRevenue_conf) ?>';
var dataVal2 = '<?php echo json_encode($ch3_arrRevenue_tent) ?>';
var dateFilter = '<?php echo json_encode($ch3_arrDate2) ?>';

Passing Decimal string from php to jquery

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.

Passing PHP-Variables to Jquery

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>

Categories

Resources