Can't pull oci array with ajax for use with ChartJs - php

I'm trying to use ChartJs and pull data from our Oracle database. I have followed the documentation as best I could and tried to adapt them for my oci output but I can't seem to get the data pulled.Here is my fetch array from data.php:
oci_execute($query);
$data = array();
while($row = oci_fetch_array($query, OCI_ASSOC)) {
$data[] = $row;
}
print json_encode($data);
Which outputs this:
[{"DT":"01-FEB-18","SHIFTS":"FIRST","TOTAL":"6","IP":"5","DOMESTIC":"2","P_RICO":"3","EXPORTS":"1"},{"DT":"31-JAN-18","SHIFTS":"SECOND","TOTAL":"66","DOMESTIC":"49","P_RICO":"4","EXPORTS":"13"},{"DT":"31-JAN-18","SHIFTS":"FIRST","TOTAL":"55","DOMESTIC":"30","P_RICO":"1","EXPORTS":"24"},{"DT":"30-JAN-18","SHIFTS":"SECOND","TOTAL":"52","DOMESTIC":"34","P_RICO":"10","EXPORTS":"8"},{"DT":"30-JAN-18","SHIFTS":"FIRST","TOTAL":"69","DOMESTIC":"55","P_RICO":"2","EXPORTS":"12"},{"DT":"29-JAN-18","SHIFTS":"SECOND","TOTAL":"61","DOMESTIC":"41","P_RICO":"10","EXPORTS":"10"},{"DT":"29-JAN-18","SHIFTS":"FIRST","TOTAL":"48","DOMESTIC":"43","P_RICO":"2","EXPORTS":"3"},{"DT":"28-JAN-18","SHIFTS":"SECOND","TOTAL":"53","DOMESTIC":"44","P_RICO":"1","EXPORTS":"8"},{"DT":"28-JAN-18","SHIFTS":"FIRST","TOTAL":"53","DOMESTIC":"43","P_RICO":"3","EXPORTS":"7"}]
The PHP variables that I'm concerned with are DT, SHIFTS, and TOTAL. On my index.php I have this ajax call to get the variables:
$.ajax({
url: "data.php",
method: "GET",
success: function(data) {
console.log(data);
var shifts = [];
var total = [];
var dt = [];
for(var i in data) {
shifts.push("Shift " + data[i].SHIFTS);
total.push(data[i].TOTAL);
dt.push(data[i].DT);
}
var chartdata = {
labels: shifts,
datasets : [
{
label: 'Shipments Complete',
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: total
}
]
};
var ctx = $("#ships");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata
});
},
error: function(data) {
console.log(data);
}
});
when I run index.php it just says that the variables are undefined.Can anyone point out where I'm going wrong?

Related

Why do I get undefined after looping an array of objects in jquery?

I want to create a bar chart using chartjs,PHP and MySql. After querying the database to get product details as a json object, now I want to iterate over the array and add product_name and price into new arrays, of which I get undefined. What might be wrong to my code?
$(document).ready(function(){
$.ajax({
url: "../controller/products-chart-data.php",
method: "GET",
success: function(data){
console.log(data);
var product = [];
var price = [];
for (var i in data) {
product.push(data[i].product_name);
price.push(data[i].price);
}
var chartData = {
labels: product,
datasets: [
{
label: "Product Price",
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: price
}
]
};
var context = $("#products-chart");
var barGraph = new Chart(context, {
type: 'bar',
data: chartData
});
},
error: function(data){
console.log(data);
}
})
})
PHP code for the database query:
<?php
$conn = mysqli_connect('localhost', 'root', '', 'shopping_cart_with_paypal');
$getAllproductsQuery = $conn->query("SELECT * FROM tbl_products");
$data = array();
foreach ($getAllproductsQuery as $row) {
$data[] = $row;
}
$getAllproductsQuery->close();
$conn->close();
print json_encode($data);
Sample data:
[{"id":"3","product_name":"Travel
bag","price":"5000","category_id":"1","product_image":"travel-
bag.jpeg","average_rating_id":"3","description":"Lather travel bag, found in
different sizes","product_code":"203"},{"id":"4","product_name":"Jewel
Box","price":"6000","category_id":"4","product_image":"jewel-
box.jpeg","average_rating_id":"5","description":"Modern jewel box straight
dubai","product_code":"204"},{"id":"5","product_name":"Wooden
Dolls","price":"9000","category_id":"5","product_image":"wooden-
dolls.jpeg","average_rating_id":"3","description":"wooden dolls made of pure
woods","product_code":"205"}]

Chart.js, PHP and JSON loop issue

I am trying to create a dashboard that will show some data from a database. Right now I am using a separate JSON encoded file named "data.php". I am using a jQuery Ajax request for this data to populate a Chart.js chart.
I have also been following an example similar to this
At the moment I am running into an issue seen here on my app.js file:
$(document).ready(function(){
$.ajax({
url: "http://{redacted ip}/swordtest/data.php",
method: "GET",
success: function(data) {
//var myData = $.parseJSON(data);
console.log(data);
var teamid = [];
var teamName = [];
var ticketCount = [];
for (var i in data) {
teamid.push("ID " + data[i].id);
teamName.push(data[i].name);
ticketCount.push(data[i].count);
}
console.log(data);
var chartData = {
lables: teamName,
datasets: [
{
label : 'Teams',
backgroundColor: 'rgba(200, 200, 200, 0.75)',
borderColor: 'rgba(200, 200, 200, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 0.75, 1)',
hoverborderColor: 'rgba(200, 200, 200, 0.75, 1)',
data: ticketCount
}
]
};
var ctx = $("#mycanvas");
var myDoughnutChart = new Chart(ctx, {
type: 'bar',
data: chartData
});
},
error: function(data) {
console.log(data);
}
});
});
What is happening though is that when I try to loop through the JSON object to separate the id's, names of the teams and amount of tickets, it will loop through the id continuously and give me this:
teamid = (1) ["ID undefined", "ID undefined"]
It will also add one and keep saying undefined. When I put breakpoints in the code it seems to only loop through the id as well. Any sort of help would be greatly appreciated. Thank you!
UPDATE
one thing to mention is that the data that I am getting from my data.php is a little different looking than the example I am working from (the link mentioned above). when I print the data it comes in this format:
data = "{"playerid":"1","score":"10"},{ "playerid":"2","score":"40"},{ "playerid":"3","score":"20"},{ "playerid":"4","score":"9"},{ "playerid":"5","score":"20"}"
Where in the example it looks like:
[{"playerid":"1","score":"10"},{ "playerid":"2","score":"40"},{ "playerid":"3","score":"20"},{ "playerid":"4","score":"9"},{ "playerid":"5","score":"20"}]
Different with brackets and without. I had a friend just try taking out the double quotes, replacing them with single quotes and wrapping the whole JSON in brackets. It seemed to start working then. I am guessing it has something to do with the way the JSON is getting formatted in my data.php.
Try to add the dataType property to the object literal that is the argument of the ajax() function. As you are getting a JSON from PHP, the property should have "json" as its value.
$.ajax({
url: "test.php",
method: "GET",
dataType: "json",
success: function(data) {
// ...
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("AJAX ERROR",textStatus,errorThrown,jqXHR);
}
});
I tested with this PHP file.
test.php
<?php
echo '[{"id":"1", "name":"John Doe", "count":"7"},{"id":"2", "name":"ABC", "count":"5"},{"id":"3", "name":"XYZ", "count":"29"}]';
?>

Error using chartJs on laravel project

I am trying to use chartJs to draw a bar chart on my laravel project but I have been getting this error -
"Failed to create chart: can't acquire context from the given item".
I have tried debugging and I think everything looks okay.
This is my JS file
$(document).ready(function () {
$.ajax({
url: "{{url('properties','totalTaxPaidByLga')}}",
method: "GET",
success: function(data) {
console.log(data);
var player = [];
var score = [];
for(var i in data) {
player.push("Player " + data[i].playerid);
score.push(data[i].score);
}
var chartdata = {
labels: player,
datasets : [
{
label: 'Player Score',
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: score
}
]
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata
});
},
error: function(data) {
console.log(data);
}
});
});
This is my blade file
<div id="chart-container">
<canvas id="mycanvas"> </canvas>
<p>Hi</p>
</div>
This is my controller
public function totalTaxPaidByLga(){
$query = DB::select("select SUM(a.settlement_amount) as totalTaxPaid, d.local_name from settlements as a, assessments as b,
property_details as c, locals as d
where a.assessment_ref = b.assessment_ref and
b.property_id = c.id and
c.lga_id = d.local_id
GROUP BY d.local_id");
foreach ($query as $row) {
$data[] = $row;
}
print json_encode($data);
}

Chart.js jQuery dropdown selected values

Hello :) (I'm novice and I learn on the job),
I work with Chart.js, jQuery, PostgreSQL
Currently I have a bar chart directly linked to PostgreSQL database.
I'd like to add a dropdown to allow the user to select a "zone", which would dynamically update the chart.
Each "zone" has different variables: population, salaries (number of employees in english), etc.
Here is the PHP
<?php
$dbconn = pg_connect("")
or die('Erreur de connexion'.pg_last_error());
$query = "SELECT id, zone_nom, zone_pop, zone_salaries FROM table";
$result = pg_query($query) or die('Query failed: ' . pg_last_error());
$array = array();
while ($row = pg_fetch_array($result, null, PGSQL_ASSOC)) {
$array[] = $row;
}
$data=json_encode($array);
echo $data;
pg_free_result($result);
pg_close($dbconn);
?>
I get the following array
[{"id":"1","zone_nom":"test ","zone_pop":"36105","zone_salaries":"15279"},{...],{...}]
Then I generate a dropdown dynamically populated by my table
But I'm stuck on how to pass the selected values ​​in the chart (and then make sure the chart gets refreshed depending on the choice in the dropdown)
<html>
<head>
<title>Liste déroulante dynamique</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/Chart.min.js"></script>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet/v1.0.3/leaflet.css" />
<script src="http://cdn.leafletjs.com/leaflet/v1.0.3/leaflet-src.js"></script>
<script type="text/javascript">
function Zone() {
$('#zone-select').empty();
$('#zone-select').append("<option>Chargement</option>");
$.ajax({
type: "POST",
url: "http://localhost/data.php",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
$('#zone-select').empty();
$('#zone-select').append("<option value='0'>-- Select zone --</option>");
$.each(data,function(i, item){
$('#zone-select').append('<option value='+data[i].zone_pop+'>'+data[i].zone_nom+'</option>');
});
$("#zone-select").change(function(){
var value = $("#zone-select option:selected").val(); // Value of selected option
console.log('Value: '+value);
});
// How to link the dropdown and the chart ?
var zoneNom = [];
var zonePop = [];
for(var i in data) {
zoneNom.push(data[i].zone_nom);
zonePop.push(data[i].zone_pop);
zoneSalaries.push(data[i].zone_salaries)
}
var chartdata = {
labels: zoneNom,
datasets : [
{
label: 'Population',
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: zonePop
},
{
label: 'Salaries',
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: zoneSalaries
}
]
};
var option = {};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata,
options: option
});
var myBarChart;
},
complete: function(){
}
});
}
$(document).ready(function(){
Zone();
});
</script>
</head>
<body>
<select id="zone-select"></select>
<div id="chart-container">
<canvas id="mycanvas"></canvas>
</div>
</body>
</html>
The value of the choice is returned
$("#zone-select").change(function(){
var value = $("#zone-select option:selected").val(); // Value of selected option
console.log('Value: '+value);
});
I am looking for but I can not find the solution for now (probably not very complicated)
Thank you in advance for your help
You could accomplish this using the following on change event handler function for your dropdown menu ...
$("#zone-select").change(function() {
var nom = $("#zone-select option:selected").text(); // name of selected option
var index = zoneNom.indexOf(nom);
var new_labels = [zoneNom[index]];
var new_data1 = [zonePop[index]];
var new_data2 = [zoneSalaries[index]];
barGraph.data.labels = new_labels;
barGraph.data.datasets[0].data = new_data1;
barGraph.data.datasets[1].data = new_data2;
barGraph.update(); // update chart
});
and, if you wish to select the first option by default, use ...
$("#zone-select").val(zonePop[0]).trigger('change');
working example
function Zone() {
$('#zone-select').empty();
$('#zone-select').append("<option>Chargement</option>");
$.ajax({
type: "GET",
url: "https://istack.000webhostapp.com/json/t9.json",
dataType: "json",
success: function(data) {
//console.log(data)
$('#zone-select').empty();
$('#zone-select').append("<option value='0'>-- Select zone --</option>");
$.each(data, function(i, item) {
$('#zone-select').append('<option value=' + data[i].zone_pop + '>' + data[i].zone_nom + '</option>');
});
$("#zone-select").change(function() {
var nom = $("#zone-select option:selected").text(); // name of selected option
var index = zoneNom.indexOf(nom);
var new_labels = [zoneNom[index]];
var new_data1 = [zonePop[index]];
var new_data2 = [zoneSalaries[index]];
barGraph.data.labels = new_labels;
barGraph.data.datasets[0].data = new_data1;
barGraph.data.datasets[1].data = new_data2;
barGraph.update(); // update chart
});
var zoneNom = [];
var zonePop = [];
var zoneSalaries = [];
for (var i in data) {
zoneNom.push(data[i].zone_nom);
zonePop.push(data[i].zone_pop);
zoneSalaries.push(data[i].zone_salaries)
}
var chartdata = {
labels: zoneNom,
datasets: [{
label: 'Population',
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: zonePop
}, {
label: 'Salaries',
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: zoneSalaries
}]
};
var option = {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata,
options: option
});
var myBarChart;
$("#zone-select").val(zonePop[0]).trigger('change'); // select first option
},
complete: function() {}
});
}
$(document).ready(function() {
Zone();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<select id="zone-select"></select>
<div id="chart-container">
<canvas id="mycanvas"></canvas>
</div>

ChartJS and Ajax calls

I would like to make charts using ChartJS and PHP ( Silex Framework )
This is my ajax call
$.ajax({ url: 'stats',
data: {method: 'dossierRepartitionType'},
type: 'post',
datatype: 'json',
success: function(output) {
dataDossierRepartitionType=output;
},
error: function () {
alert("Oops there is an error.");
}});
This is my PHP function which i managed to call
public function dossier(){
$stmt = "SELECT count(*) FROM dossier GROUP BY typedossier";
$stmt = $this->db->prepare($stmt);
$rows=$stmt->execute();
$rows = $stmt->fetch(PDO::FETCH_NUM);
return ?????
}
And here is my chart :
var ctx = document.getElementById("myChart");
ctx.width = 400;
ctx.height = 400;
data = {
datasets: [{
data: [dataDossierRepartitionType, 20],
backgroundColor: [
'rgb(255, 99, 132)',
'rgb(54, 162, 235)',
],
borderColor: [
'white',
'white',
],
borderWidth: 1
}],
// These labels appear in the legend and in the tooltips when hovering different arcs
labels: [
'Red',
'Blue',
]
};
var myDoughnutChart = new Chart(ctx, {
type: 'doughnut',
data: data,
options: {
legend: {
labels: {
fontColor: "white",
fontSize: 18
}
},
maintainAspectRatio: false,
responsive: false
}
});
Route.php
$app->post('/stats', function () use ($app) {
session_start();
if(isset($_POST['method']) && !empty($_POST['method'])) {
$method = $_POST['method'];
switch($method) {
case 'dossierRepartitionType' :
$dossiers=$app['dao.dossier']->dossierRepartitionType();
break;
}
}
return new ResponseSilex("$dossiers");
});
So my AJAX call the route and then get the result of the function into $dossiers which is ouput in the Reponse, am i doing it right ?
How can i return an array with all the datas value for each count ?
I struggle to catch error and to find a proper way to bind MYSQL count value to my chart
Thank you
The main idea is that you should format your data in your model, then return JSON to the front end via json_encode. After that, you would parse the json in your ajax returns and then pass the appropriate data to the chart.
it's very easy, you need to modify your php code like this:
public function dossier(){
$stmt = "SELECT count(*) as total FROM dossier";
$stmt = $this->db->prepare($stmt);
$rows=$stmt->execute();
$number_of_rows = $rows->fetchColumn();
return json_encode(["total" => $number_of_rows]);
In your ajax petition you are specifying a "json" return so in your script php need's return a json.
$.ajax({ url: 'stats',
data: {method: 'dossierRepartitionType'},
type: 'post',
datatype: 'json',
success: function(output) {
dataDossierRepartitionType=output.total;
},
error: function () {
alert("Oops there is an error.");
}});
You should to receive a json from php with this structure
{total: rows_total}
so in your ajax response you'll receive that answer and you can get the data like this:
dataDossierRepartitionType=output.total;
Sorry for my english, hope can help you
You can send JSON data from php
Try this:
Php:
public function dossier(){
$stmt = "SELECT count(*) FROM dossier GROUP BY typedossier";
$stmt = $this->db->prepare($stmt);
$rows=$stmt->execute();
$rows = $stmt->fetch(PDO::FETCH_NUM);
exit(json_encode(array('counts' => $rows)));
}
After ajax successfully complete you need to initialize chart plugin inside success callback like below:
Ajax:
$.ajax({ url: 'stats',
data: {method: 'dossierRepartitionType'},
type: 'post',
datatype: 'json',
success: function(output) {
if (output.counts) {
dataDossierRepartitionType=output.counts.join();
alert(dataDossierRepartitionType)
initCharts(dataDossierRepartitionType);
}
},
error: function () {
alert("Oops there is an error.");
}});
Finally wrap chart initialization code inside callback function
Chart:
function initCharts(dataDossierRepartitionType){
var ctx = document.getElementById("myChart");
ctx.width = 400;
ctx.height = 400;
data = {
datasets: [{
data: [dataDossierRepartitionType, 20],
backgroundColor: [
'rgb(255, 99, 132)',
'rgb(54, 162, 235)',
],
borderColor: [
'white',
'white',
],
borderWidth: 1
}],
// These labels appear in the legend and in the tooltips when hovering different arcs
labels: [
'Red',
'Blue',
]
};
var myDoughnutChart = new Chart(ctx, {
type: 'doughnut',
data: data,
options: {
legend: {
labels: {
fontColor: "white",
fontSize: 18
}
},
maintainAspectRatio: false,
responsive: false
}
});
}

Categories