Data will not draw onto my chart - php

I am trying to output data onto a chart using the chart.js lib. I have successfully pulled the data out I need and created the datasets but for some reason it just will not render onto the chart.
I have three files:
teamData.js
$(document).ready(function(){
$.ajax({
url : "http://localhost/acredashAdv/teamData.php",
type : "GET",
success :function(data){
console.log(data);
var score_1 = [];
var score_2 = [];
for (var i in data) {
score_1.push(data[i].score_1);
score_2.push(data[i].score_2);
}
var chartata = {
labels: [
"Strategic Development and Ownership",
"Driving change through others",
"Exec Disposition",
"Commercial Acumen",
"Develops High Performance Teams",
"Innovation and risk taking",
"Global Leadership",
"Industry Leader"
],
datasets : [
{
label: "user 1",
backgroundColor: "rgba(0,0,0,0)",
borderColor: "#B71C1C",
data: score_1,
},
{
label: "user 2",
backgroundColor: "rgba(0,0,0,0)",
borderColor: "#B71C1C",
data: score_2
},
]
};
var ctx = $("#mycanvas");
var LineGraph = new Chart(ctx, {
type: 'radar',
data: chartata,
animationEasing: 'linear'
});
},
error :function(data){
},
});
});
teamData.php
<?php
include 'config.php';
$query = sprintf("SELECT member_id, firstName, lastName, score_1, score_2, score_3, score_4, score_5, score_6, score_7, score_8 FROM members");
$result = $conn->query($query);
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
$result->close();
$conn->close();
print json_encode($data);
?>
teams.php
<div style="max-width: 500px;">
<canvas id="mycanvas" class="container"></canvas>
</div>
On my console.log I can see the data is coming through correctly:
[{"member_id":"144","firstName":"Dan","lastName":"Barrett","score_1":"4","score_2":"2","score_3":"3","score_4":"5","score_5":"1","score_6":"3","score_7":"5","score_8":"4"},{"member_id":"145","firstName":"Jon","lastName":"Smith","score_1":"3","score_2":"4","score_3":"1","score_4":"2","score_5":"1","score_6":"2","score_7":"3","score_8":"4"},{"member_id":"146","firstName":"Dan","lastName":"Barrett","score_1":"1","score_2":"2","score_3":"1","score_4":"1","score_5":"4","score_6":"1","score_7":"4","score_8":"3"}]
But unless I am getting mixed up it will not draw out the data... I end up with an empty chart.

Maybe could be the version of your Chart.js, here is your code running:
https://jsfiddle.net/6xdvj5u3/
Using this version of Chart.js
https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.4/Chart.bundle.min.js
try to take the PabloMartinez's recommendation adding a header to your PHP file, before your print line:
header('Content-type: application/json');
print json_encode($data);

Related

Selectbox issue

I have an issue with my code below. I populated my selectbox from my db which works fine. But when I select an option it wont send the value to my other php file I am relative new to jQuery so I hope that I have a small error in my code I hope that someone can help me.
$(document).ready(function() {
$("#button1").click(function(){
var dropd = $("#drop").val();
$.getJSON('data.php?id='+dropd)
So when I press button1 it should put the value from my selectbox in the variable dropd and send it to the php site data.php right?
So this is the code for my select box which should be alright.
<select id ="drop">
<option disabled selected>--Wähle Station aus--</option>
<?php
$records = mysqli_query($db, "SELECT idStation, Stationname FROM station WHERE fi_idFirma = $id");
while($data = mysqli_fetch_array($records))
{
echo "<option value='".$data['idStation']."'>" .$data['Stationname']."</option>";
}
?>
</select>
My problem is I think that i want several codes to start at once in jquery because when i press button1 it loads the value from dropd to data.php and than it should load an json file where i populate my graphs with.
$(document).ready(function() {
$("#button1").click(function(){
var dropd = $("#drop").val();
$.getJSON('data.php?id='+dropd)
function grab() {
return new Promise((resolve, reject) => {
$.ajax({
url: "data.php",
method: "GET",
success: function(data) {
resolve(data)
},
error: function(error) {
reject(error);
}
})
})
}
grab().then((data) => {
console.log('Recieved our data', data);
let Zeit = [];
let Luft = [];
try {
data.forEach((item) => {
Zeit.push(item.Zeit)
Luft.push(item.Luftfeuchtigkeit)
});
let chartdata1 = {
labels: [...Zeit],
datasets: [{
label: 'Luftfeuchtigkeit',
backgroundColor: 'rgba(200, 200, 200, 0.75)',
borderColor: 'rgba(200, 200, 200, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: [...Luft]
}]
};
let ctx = $("#myChart1");
let barGraph = new Chart(ctx, {
type: 'line',
data: chartdata1
});
} catch (error) {
console.log('Error parsing JSON data', error)
}
}).catch((error) => {
console.log(error);
})
I know it looks a bit messy but i hope that you can help me in this case.
This is the data.php file where the select value should arrive.
<?php
header('Content-Type: application/json');
$conn = mysqli_connect("localhost","root","","usera01");
$id = isset($_GET['dropd']) ? $_GET['dropd'] : false;
if ($id) {
echo ($_GET['dropd']);
} else {
$id = 1;
}
$sqlQuery = "SELECT idDatenNr, Luftfeuchtigkeit, Lichtverhältnis, Bodenfeuchtigkeit,Temperatur, Zeit, fi_idStation FROM daten WHERE fi_idStation = '$id'";
$result = mysqli_query($conn,$sqlQuery);
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
mysqli_close($conn);
echo json_encode($data);
?>
Maybe i made here an mistake.

How to populate Jvector Map with countries from database?

(I am new to Javascript and jQuery..) I have a dashboard and I want to display a map that shows the countries where participants of a particular event are coming from. With this, I opted with Jvector Map. I am having a hard time displaying the countries in the map, coming from my database.
dashboard.js
var mapData = {};
$('#world-map').vectorMap({
map: 'world_mill_en',
backgroundColor: "transparent",
regionStyle: {
initial: {
fill: '#e4e4e4',
"fill-opacity": 0.9,
stroke: 'none',
"stroke-width": 0,
"stroke-opacity": 0
}
},
series: {
regions: [{
values: function() {
$.ajax({
url:"includes/sql/fetchcountries.php",
method:"GET",
data:mapData,
dataType:"json",
success: function(data){
mapData = data;
console.log(mapData);
}
})
},
scale: ["#1ab394", "#22d6b1"],
normalizeFunction: 'polynomial'
}]
},
});
fetch.php
<?php
require '../auth/dbh.inc.auth.php';
$id = $_SESSION['ntc_id'];
$stmt = $conn->prepare("SELECT DISTINCT(participants.p_country) FROM ntc_participants
INNER JOIN participants ON participants.p_id=ntc_participants.p_id_fk
WHERE ntc_participants.ntc_id_fk=?");
$data = array();
mysqli_stmt_bind_param($stmt, "i", $id);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows === 0);
if($row = $result->fetch_assoc()) {
$data[] = [
$row['p_country'] => 0 ]; //the value 0 is just a placeholder.. The jvector map feeds on this format: "US":298, "SA": 200
}
echo json_encode($data);
?>
Could anyone be gracious enough to walk me through all the wrong things I'm doing in my code? Appreciate all the help! :)
Ajax is asynchronous, so You are creating the map before the data has been downloaded.
Initialize the map with empty values for Your region:
$('#world-map').vectorMap({
...
values: {}
...
});
Then, whenever You need to show the data, set it dynamically:
$.get("includes/sql/fetchcountries.php", function(data) {
var mapObj = $("#world-map").vectorMap("get", "mapObject");
mapObj.series.regions[0].setValues(data);
});
During the ajax invocation and data download maybe You can show a spinner (please look at beforeSend inside the jQuery full ajax documentation: https://api.jquery.com/jquery.ajax/).
Here is the reference for setValues:
http://jvectormap.com/documentation/javascript-api/jvm-dataseries/
http://api.worldbank.org/v2/country/all/indicator/NY.GDP.PCAP.PP.CD?format=json&date=2018
This link will give you up-to-date stats for most common indicators via json - and then you can pluck whatever data that you like. I don't have all the code yet, as I am working on this today too.
This answers the question above whenever your database can also present JSON
document.addEventListener('DOMContentLoaded', () => {
console.log("loaded")
fetchCountryData()
})
function fetchCountryData () {
fetch('http://api.worldbank.org/v2/country/all/indicator/NY.GDP.PCAP.PP.CD?format=json&date=2018')
//
.then(resp => resp.json())
.then(data => {
let country.id = data[1]
let indicator.id = data[1]
create-GDP-Data(country.id,indicator.id)
})
}
function create-GDP-Data(country.id,indicator.id){
let gdpData = ?
}
$('#world-map-gdp').vectorMap({
map: 'world_mill',
series: {
regions: [{
values: gdpData,
scale: ['#C8EEFF', '#0071A4'],
normalizeFunction: 'polynomial'
}]
},
onRegionTipShow: function(e, el, code){
el.html(el.html()+' (GDP - '+gdpData[code]+')');
}
});

multiple ajax requests from one page + how to do + best practice

I am working on google charts at the minute and I have got a basic one setup.
What it does at present is connects to a DB and returns a dataset based on 1 query. I am wondering is, if I want to draw more charts with different queries to the database how do I do this? Or what is the best practice?
For instance, there is already one connection with one query, how can I add another query, and then draw the charts based on what is returned?
I understand that might be a broad question, but maybe someone could show me how I would return a different query/dataset from the DB?
This is my code:
$(document).ready(function(){
console.log("hello world")
//alert("result")
$.ajax({
url:"data.php",
dataType : "json",
success : function(result) {
google.charts.load('current', {
'packages':['corechart','bar']
});
google.charts.setOnLoadCallback(function() {
console.log(result[0]["name"])
drawChart(result);
});
}
});
//add a 2nd call - will need a 2nd draw charts to draw the different dataset assuming it will be different
// - will need a 2nd data.php as the query will be different on the dataset
$.ajax({
url:"data.php",
dataType : "json",
success : function(result2) {
google.charts.load('current', {
'packages':['corechart','bar']
});
google.charts.setOnLoadCallback(function() {
console.log(result2[0]["name"])
drawChart(result2);
});
}
});
function drawChart(result) {
var data = new google.visualization.DataTable();
data.addColumn('string','Name');
data.addColumn('number','Quantity');
var dataArray=[];
$.each(result, function(i, obj) {
dataArray.push([ obj.name, parseInt(obj.quantity) ]);
});
data.addRows(dataArray);
var piechart_options = {
title : 'Pie Chart: How Much Products Sold By Last Night',
width : 400,
height : 300
}
var piechart = new google.visualization.PieChart(document
.getElementById('piechart_div'));
piechart.draw(data, piechart_options)
var columnchart_options = {
title : 'Bar Chart: How Much Products Sold By Last Night',
width : 400,
height : 300,
legend : 'none'
}
//var barchart = new google.visualization.BarChart(document
// .getElementById('barchart_div'));
//barchart.draw(data, barchart_options)
var chart = new google.charts.Bar(document.getElementById('columnchart_material'));
chart.draw(data, google.charts.Bar.convertOptions(columnchart_options));
} //have added this column chart but need to wrok out if it is best practice????
});
I am getting an object back from my DB query, but I want to know how to return more/different datasets from the same DB connection? For example what if I wanted to draw another chart with the dataset returned from this query select * from product where name="Product1" OR name="Product2";
0: Object { id: "1", name: "Product1", quantity: "2" }
​1: Object { id: "2", name: "Product2", quantity: "3" }
​2: Object { id: "3", name: "Product3", quantity: "4" }
​3: Object { id: "4", name: "Product4", quantity: "2" }
​4: Object { id: "5", name: "Product5", quantity: "6" }
​5: Object { id: "6", name: "Product6", quantity: "11" }
For what it is worth my php code is as follows:
data.php
<?php
require_once 'database.php';
$stmt = $conn->prepare('select * from product');
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_OBJ);
echo json_encode($results);
?>
database.php
<?php
$conn = new PDO('mysql:host=192.168.99.100;dbname=demo','root', 'root');
?>
note: this might be of interest
google charts only needs to be loaded once per page load,
not every time you need to draw a chart
also, google.charts.load can be used in place of --> $(document).ready
it will wait for the page to load before executing the callback / promise
recommend setup similar to following snippet...
google.charts.load('current', {
packages: ['corechart', 'bar']
}).then(function () {
$.ajax({
url: 'data.php',
dataType: 'json'
}).done(drawChart1);
$.ajax({
url: 'data.php',
dataType: 'json'
}).done(drawChart2);
});
function drawChart1(result) {
...
}
function drawChart2(result) {
...
}

DataTable dataset with JSON

I'm trying to use DataTable to show all fields of my JSON, but I'm not understand how to use it.
I just need how to populate dataset correctly to read data.
<script>
<?php
var jqxhr = $.ajax({url: api_ricerca_ingredienti, type: "GET",dataType: "json", data: {all: 1, ln : "it",completo:"-1",conteggio: 1}} )
var max=json.items.length;
for (i=0;i<max;i++){
var el=json.items[i];
}
$(".risultato_ricerca").click(function() {
carica_ingrediente($(this).attr('data-id'));
});
})
<?php }?>
var dataSet = [
/*HOW?*/
];
$(document).ready(function() {
$('#example').DataTable( {
data: dataSet,
columns: [
{ title: "Nome" },
{ title: "Stato" },
{ title: "Home" },
{ title: "Utente" },
{ title: "Mi piace" },
{ title: "Contributi" }
]
} );
} );
</script>
<table id="example" class="table table-responsive table-hover table-dynamic filter-head"></table>
First, two comments about your code.
As #Patrick Q stated, your PHP tags are useless: you are writing Javascript, PHP is another things that has nothing to do with your code, so remove <?php and <?php }?>
Then, i can't understand this code:
for (i=0;i<max;i++){
var el=json.items[i];
}
This for is completely useless. you cycle through every element in json.items without performing any operation. At the end you just store the last json.items in the el (without even using el in your code).
By the way, your main question:
As said in the official documentation, your dataSet must contain an array for every row of your table in the format:
var dataSet = [
["john","italy","home","john",15,20],
["john","italy","home","john",15,20]
]
This example will create two identical rows with random data inside.
Assuming every item in your json has name country home user likes contribs fields you will need something like that:
var dataSet = [];
for (i=0;i<json.items.length;i++){
var el = [json.items[i].name,json.items[i].country, json.items[i].home, json.items[i].user, json.items[i].likes, json.items[i].contribs]
dataSet[i] = el;
}
Sorry guys. I've truncated my prev code. Now the building of data array works like a charm. I've just a doubt about a console error:
"jquery.dataTables.min.js:5 Uncaught TypeError: Cannot read property 'aDataSort' of undefined"
I can't show my rows. According with your opinion, what's the problem?
Thank you!
<script>
< ?php
if (isset($_GET) && isset($_GET['id'])){
?>
$( document ).ready(function() {
carica_ingrediente('<?php echo $_GET['id'];?>');
});
<?php }else {?>
$('#query').keypress(function(e) {
if (e.keyCode == $.ui.keyCode.ENTER) {
$('#cerca').click();
}
});
$(document).ready(function() {
var jqxhr = $.ajax({url: api_ricerca_ingredienti, type: "GET",dataType: "json", data: {all: 1, ln : "it",completo:"-1",conteggio: 1}} )
.done(function(json) {
if (json.res==0){
alert( "Inserisci una parola per iniziare la ricerca " );
return;
}
var dataSet = [];
for (i=0;i<json.items.length;i++){
var el = [json.items[i].nome,json.items[i].completo, json.items[i].home, json.items[i].utente, json.items[i].likes, json.items[i].countingredienti];
dataSet[i] = el;
console.log(el);
}
$(".risultato_ricerca").click(function() {
carica_ingrediente($(this).attr('data-id'));
});
$(document).ready(function() {
$('#example').DataTable( {
data: dataSet,
columns: [
{ title: "Nome" },
{ title: "Stato" },
{ title: "Home" },
{ title: "Utente" },
{ title: "Mi piace" },
{ title: "Contributi" }
]
} );
} );
})
.fail(function() {
alert( "error" );
});
});
<?php }?>
</script>

Highcharts Pie Chart via AJAX/JSON: But Slice Errors and Json Format Not Correct?

I'm a newbie php/js/mysql programmer.
I'm trying to create a pie chart in highcharts using jquery, where the data is discovered dynamically via ajax from echo json_encode in php (includes a select query from mysql).
Two problems:
1) The pie chart has these trailing "Slice: 0 %" flares everywhere. Don't know where these are coming from, what it means, nor how to fix it.
2) Json is new to me. The json data feed appears to be getting through (firebug sees it), but the format looks like this. I'm trying to boil it down to name and percent number only. Like this ['Pages', 45.0] but not sure how. Is this done in the json/php or should it be done in the sql query itself?
[{"contenttype":"BLOGPOST","count(*)":"2076"},{"contenttype":"COMMENT","count(*)":"2054"},{"contenttype":"MAIL","count(*)":"29448"},{"contenttype":"PAGE","count(*)":"33819"}]
Any help much appreciated
The highcharts js file is here:
//Define the chart variable globally,
var chart;
//Request data from the server, add it to the graph and set a timeout to request again
function requestData() {
$.ajax({
url: 'hc1.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20; // shift if the series is longer than 20
// add the point
chart.series[0].addPoint(point, true, shift);
// call it again after one second
setTimeout(requestData, 1000);
},
cache: false
});
}
$(document).ready(function(){
//Create the test chart
chart = new Highcharts.Chart({
chart: {
renderTo: 'mycontainer2',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
events: {load: requestData}
},
title: {text: 'Content Types in Wiki'},
tooltip: {formatter: function() {return '<b>'+ this.point.name +'</b>: '+ this.percentage +' %';}
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
//color: Highcharts.theme.textColor || '#000000',
//connectorColor: Highcharts.theme.textColor || '#000000',
formatter: function() {
return '<b>'+ this.point.name +'</b>: '+ this.percentage +' %';
}
}
}
},
series: [{
type: 'pie',
name: 'Content',
data: []
}]
});
The php file is here:
<?php
// Set the JSON header
header("Content-type: text/json");
// Connect to db
include('dbconnect.php');
// Count version 1 of content types of interest
$query = ("select contenttype, count(*)
from CONTENT
where version='1' and contenttype='page' or contenttype='comment' or contenttype='blogpost' or contenttype='mail' or contenttype='drafts'
group by CONTENT.contenttype;");
// execute query
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
// create a php array and echo it as json
//$row = mysql_fetch_assoc($result);
//echo json_encode($row);
$results = array(); while ( $row = mysql_fetch_assoc( $result )) { $results[] = $row; }
echo json_encode($results);
?>
First problem, how do you get your data into a format that highcharts is going to accept (namely arrays of arrays, [[name,percent],[nextname,percent],etc])? I would handle this in your PHP:
<snip>
// execute query
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
$total = 0;
$results = array();
while ( $row = mysql_fetch_assoc( $result )) {
$results[$row["contenttype"] = $row["count()"];
$total += $row["count()"];
}
$forHigh = array();
foreach ($results as $k => $v) {
$forHigh[]=array($k,($v/$total) * 100); // get percent and push onto array
}
echo json_encode($forHigh); // this should be an array of array
Now that our JSON returned structure is ready for HighCharts, we just need to call the plot creation once after our JSON call to create the plot. I would do it in the success callback of the $.ajax call.
$.ajax({
url: 'hc1.php',
success: function(jsonData) {
chart = new Highcharts.Chart({
<snip>
series: [{
type: 'pie',
name: 'Content',
data: jsonData
}]
<snip>
},
cache: false
});

Categories