highchart use ajax to php+mysql - javascript

I use highchart on the leaflet map. I use ajax to grab the data in php. I can see the data returned in console.log, but I can't draw a line chart. Is there any problem?
I directly write php,js and html in a program code can be displayed, the data format I have not changed.
This is my result
This is console.log show
This is my html code:
<div class="inner">
<div id="map" style="width: 600px; height: 400px;"></div>
<script src="assets/js/leaflet2.js"></script>
</div>
leaflet2.js
function onClick(e){
var popup = e.target.getPopup();
var content = popup.getContent();
var find_1 = content.indexOf('>');
var find_2 = content.indexOf('/');
var id = content.substring(find_1+1,find_2-1);
$.ajax({
type: 'POST',
url: 'http://localhost/html5up-helios/chart.php',
data: {
"device":id
},
success:function(data){
// console.log(data);
var modify = data.indexOf('[');
var show = data.substring(modify);
console.log(show);
var chart = new Highcharts.Chart({
chart: { height: 175, width: 300 ,
renderTo: 'container'}, 
title: { text: '' },
series: [{
name: 'PM 2.5',
data: show
}
],
credits: {
enabled: false
},
exporting:{
enabled:false
}
});
}
});
}
chart.php
<?php
include("connection.php");
if (isset($_POST["device"])) {
$id = $_POST["device"];
error_log(print_r($id, true));
} else {
error_log(print_r("error", true));
}
try {
$sql = "SELECT * FROM day WHERE DATE_SUB(curdate(), INTERVAL 20 DAY) <= date(date)";
if ($stmt = $db->query($sql)) {
while ($result = mysqli_fetch_array($stmt)) {
$number_pm = intval($result['pm25']);
if ($number_pm < 0) {
$number_pm = 0;
}
$pm25[] = array(
$result['date'], $number_pm
);
}
$pm25 = json_encode($pm25);
echo $pm25;
}
} catch (Exception $e) {
die($e);
}
?>
In addition to this, isset ($ _ POST ["device"]) in my php will display an error, but I have to pass the data out in leaflet.js(
$ .ajax ({
type: 'POST',
url: 'http: //localhost/html5up-helios/chart.php',
data: {
"device": id
},});
)
php doesn't seem to receive anything, or am I wrong?

Related

Grid webix with url column click

just created a table in webix, I have a "TBD" column where I display a URL, my question is: how to make this URL https://pops.dra.com/TBD.php?jour=$adep&arc=$ads clickable please?
while($row = mysqli_fetch_array($requete, MYSQLI_ASSOC)) {
$row_array['ac'] = $row["TA"];
$row_array['ad'] = $row["day"];
$ad = $row["day"];
$row_array['ads'] = $row["arc"];
$ads = $row["arc"];
$row_array['eob'] = $row["pl"];
$row_array['linkjournal'] = "https://pops.dra.com/TBD.php?jour=$adep&arc=$ads";
array_push($small_film_set2, $row_array);
}
}
$date_update = $small_film_set2[1]['adep'];
?>
var small_film_set2 = <?php echo json_encode($small_film_set2) ?>;
webix.ready(function(){
grid = webix.ui({
container:"testA",
view:"datatable",
columns:[
{ id:"index", header:"TA", sort:"int"},
{ id:"ac", header:["CT", {content:"selectFilter"}],width:120, sort:"string"},
{ id:"ad", header:["Date", {content:"textFilter"}] , width:120, sort:"int"},
{ id:"ads", header:["Arcid", {content:"textFilter"}], width:100, sort:"string"},
{ id:"eob", header:["Pl", {content:"textFilter"}], width:100, sort:"string"},
{ id:"linkjournal", header:["TBD"], width:220, sort:"string"}
//{ id:"ssr", header:"Nb", width:100, sort:"int", header:[ "nb", {content:"summColumn" }] }
],
autoheight:true,
autowidth:true,
data:small_film_set2,
on:{
"data->onStoreUpdated":function(){
this.data.each(function(obj, i){
obj.index = i+1;
})
}
}
});
});
Thanks for your help
Define a column template, there you can add html elements, e.g.:
{
id:"linkjournal", header:["TBD"],
width:220, sort:"string",
template: obj => `link text`
}

Updating server from Kendo Color picker inside kendo grid

The Problem
So i am currently trying to implement a color picker inside of a Kendo grid, that will hopefully send the chosen color to my Sql Table. Unfortunately, It doesn't seem as though the Update controller is being reached. I am relatively new to Kendo UI, so there might be some incredibly dumb errors shown.
Questions
I guess my main question would be: How can i call the update method when update is clicked on the grid. Essentially, the color picker and the edit command are showing up in beautiful fashion. I just want to know how i can be sure that the method is being called when 'Update' is clicked, seeing as it is not reaching my controller. Feel free to ask if you need to see more code or perhaps a screen shot.
Code
Config.cshtml ( Grid )
#model IEnumerable<STZN.Models.AGCData.ErrorCode>
#{
ViewBag.Title = "Config";
}
#section HeadContent{
<script src="~/Scripts/common.js"></script>
<script>
$(document).ready(function () {
$("#grid").kendoGrid({
editable: "inline",
selectable: "row",
dataSource: {
schema: {
model: {
id: "error_code",
fields: {
color: { type: 'string' }
}
}
},
transport: {
read: {
type: "POST",
dataType: "json",
url: "#Url.Action("ErrorCodes")"
},
update: {
type: "POST" ,
dataType: "json",
url: "#Url.Action("UpdateErrorCodes")",
}
}
},
columns: [
{ command : [ "edit" ] },
{
field: "error_code", title: "Error Code",
},
{
field: "error_description", title: "Error Description"
},
{
field: "color",
width: 150,
title: "Color",
template: function (dataItem) {
return "<div style = 'background-color: " + dataItem.color + ";' </div>"
},
editor: function (container, options) {
var input = $("<input/>");
input.attr("color",options.field);
input.appendTo(container);
input.kendoColorPicker({
value: options.model.color,
buttons: false
})
},
}
]
});
});
</script>
}
Update Controller
public JsonResult UpdateErrorCodes(ErrorCode model)
{
using (var db = new AgcDBEntities())
{
db.Entry(model).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
db.Configuration.ProxyCreationEnabled = false;
var data = db.ErrorCodes.Where(d => d.error_code == model.error_code).Select(x => new
{
error_code = x.error_code,
description = x.error_description,
color = x.color,
});
return new JsonResult()
{
JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.AllowGet,
};
}
}
I actually managed to fix my issue by adding an additional input attribute to my editor function in the "color" field. It looks like this:
input.attr("data-bind","value:" + options.field);
There are still some present issues (unrelated to the fix/server update) , but as far as updating to the server, It work's as intended.

post callback function synchronization

I'm using datatables and after post I want to refresh the page after changes in the database are done. But for now it's pretty much random if the page refreshes before or after the database is updated. I also tried to add 'success:' to the callback function but this doesn't help.
Script for datatables projects.php:
<script> $(document).ready( function () {
var projects = $('#projects').DataTable({
paging:true, dom: 'Blfrtip', colReorder: true, select: {style: 'single'},
buttons: [
{
text: 'Edit',
action: function () {
$projectID = $(projects.row('.selected').node()).data('id');
if ($projectID === undefined)
{
alert("Please select a project.");
} else {
window.location.href = "../projects/editProject.php?projectID=" + $projectID;
}
}
},
{
text: 'Add',
action: function () {
window.location.href = "../projects/addProject.php";
}
},
{
text: 'Delete',
action: function () {
$projectID = $(projects.row('.selected').node()).data('id');
if ($projectID === undefined)
{
alert("Please select a project.");
} else {
$.post("../projects/deleteProject.php",
{
projectID: $projectID,
function() {
window.location.reload(true);
}
}
);
}
}
}
] }); } ); </script>
deleteProject.php:
<?php
require("../database/dbService.php");
require("../projects/deleteProjectService.php");
session_start();
$connection = connectToDB();
// check if input data is set
if (!isset($_POST['projectID'])){
header("Location: ../projects/projects.php");
exit;
}
// input data
$projectID = $_POST['projectID'];
deleteProject($connection, $projectID);
$_SESSION['message'] = "The project has been deleted!";
?>
You placed callback function in the wrong place, it should have been:
$.post(
"../projects/deleteProject.php",
{ projectID: $projectID },
function(){ window.location.reload(true); }
);

Trouble showing results with pie highchart

I'm totally new to Highcharts and I made two types of them: spline and pie. They now look like this:
And this:
The problem I have can be seen immediately. Since I have two buttons on which user can determine how he wants his chart to appear:
I succeed to update chart type like so:
$('#pie').click(function(){
if($('#pie').hasClass('active')!=true){
$('#spline').removeClass('active');
$('#pie').addClass('active');
$('#curve_chart').highcharts().series[0].update({
type: "pie"
});
}
});
But I don't want this pie chart to appear like this. I want, like in spline type that values represent each day, not Notiflow:35 etc. This is code responsible for charts:
var type='';
$('#spline').click(function(){
if($('#spline').hasClass('active')!=true){
$('#pie').removeClass('active');
$('#spline').addClass('active');
$('#curve_chart').highcharts().series[0].update({
type: "spline"
});
}
});
$('#pie').click(function(){
if($('#pie').hasClass('active')!=true){
$('#spline').removeClass('active');
$('#pie').addClass('active');
$('#curve_chart').highcharts().series[0].update({
type: "pie"
});
}
});
$(function () {
if($('#spline').hasClass('active')){
type='spline';
}else{
type='pie';
}
$('#curve_chart').highcharts({
chart: {
type: type
},
title: {
text: 'Click through rate:'
},
xAxis: {
categories: [<?php foreach ($percentagePerDay as $key => $value) {
if ($value != $last) {
echo substr($key, -2);
echo ',';
} else {
echo substr($key, -2);
}
}?>]//key
},
yAxis: {
title: {
text: 'Percentage'
}
},
series: [{
name: '<?= $name ?>',
data: [<?php foreach ($percentagePerDay as $key => $value) {
if ($value != $last) {
echo $value;
echo ',';
} else {
echo $value;
}
}?>]//value
}]
});
});
I tried to make pie chart to represent hard coded values like so:
$('#pie').click(function(){
if($('#pie').hasClass('active')!=true){
$('#spline').removeClass('active');
$('#pie').addClass('active');
$('#curve_chart').highcharts().series[0].update({
type: "pie"
series:[{
data:[['11',35],['12',15],['13',30],['14',20]]
}]
});
}
});
}
});
But pie highchart didn't changed. What more do I need to add to this line(except of type):
$('#curve_chart').highcharts().series[0].update({});
in order for my pie to represent values for each day within range like spline does and to remove those 'slice' moments?
UPDATE:
So, this is how I want my pie to look:
When updating series o not pass series in object - only series properties, like name, type, data, etc. To have dataLabels like in the image you only will need to set names for points, Highcharts will make it work.
Example: http://jsfiddle.net/tvd6faf9/

How to add {text} (without quotes) to an array in PHP for Google Chart API?

Updated following Uberfuzzy advice:
$a = '{"role": "tooltip","p": {"html": true}}';
$aa = json_decode($a,true);
$data[0] = array_merge(array(product),$info,array($aa));
This thread shows how to customize the html content of the tooltip in Google Chart API using arrayToDataTable. It requires the format like this:
[
['Country', 'Value', {role: 'tooltip', p:{html:true}}],
['Russia', 5, 'Hello world<br>test'],
['US', 20, '<img src="logo6w.png"/>']
]
Fiddle Example.
I was using AJAX to generate a JSON output from mysql and pass into arrayToDataTable function. The code below gives me this output:
[["product","diameter","width"],["Product 1",2,4],["Product 2",4,8]]
$_POST["info"] Content:
Array
(
[0] => diameter
[1] => width
)
PHP Code:
$rows = $users->fetchAll();
$data="";
$data[0] = array_merge(array(product),$info);
$i = 1;
foreach ($rows as $row)
{
$d[]=$row["name"];
foreach($_POST["info"] as $p)
{
$d[]= $row[$p];
}
$data[$i] = $d;
$d=array(); //set $d to empty not to get duplicate results
$i++;
}
echo json_encode($data,JSON_NUMERIC_CHECK);
How can I insert {role: 'tooltip', p:{html:true}} in $data[0]? It isn't an array, so I can't simply use
$data[0] = array_merge(array(product),$info,array({role: 'tooltip', p:{html:true}}));
jQuery:
function drawChart() {
var info = $('input:checked').map(function(){
return $(this).val()
}).get();
var tt = $('.tt').map(function(){
return $(this).data('tid')
}).get(); console.log(tid);
var title = $('h3').text()
var jsonData = $.ajax({
url: "test.php",
type:"POST",
dataType: "json",
data:{'info[]':info,'tt':tt},
async: false
}).responseText;
var data = google.visualization.arrayToDataTable($.parseJSON(jsonData));
var options = {
tooltip: {isHtml: true},
hAxis: {
textStyle: {fontSize: 11},
slantedText: true,
slantedTextAngle: 40
}
};
var chart = new google.visualization.LineChart(
document.getElementById('chart'));
chart.draw(data, options);
}
It looks like your {role: 'tooltip', p:{html:true}} is json, so run json_decode (remember to pass true as the 2nd param) on it to get a php native array, THEN do your array merging.
json_encode converts PHP's associative arrays to javascript objects, so to create {role: 'tooltip', p:{html:true}}, you would create a PHP array like this:
$jsObj = array(
'role' => 'tooltip',
'p' => array(
'html' => true
)
);

Categories