Create nested dynamic json with mysql data in php? - php

I want to display year and month in json format.Below is my json to get data but it not looks that i want please help me to get proper json.
<?php
include 'conn.php';
$year= array();
$sql = mysqli_query($conn,'SELECT SALARY_SLIP_ID,ORG_ID,EMPLOYEE_ID,PAY_MONTH,PAY_YEAR FROM india_salary_slip_details where EMPLOYEE_ID = 31');
while ($row = mysqli_fetch_array($sql ,MYSQLI_ASSOC))
{
$year[] = array(
'PAY_YEAR' => $row['PAY_YEAR'],
'PAY_MONTH' => $row['PAY_MONTH'],
);
}
echo json_encode($year);
?>
json data that i got with this is :
[
{
"PAY_YEAR": "2014",
"PAY_MONTH": "February"
},
{
"PAY_YEAR": "2014",
"PAY_MONTH": "April"
},
{
"PAY_YEAR": "2014",
"PAY_MONTH": "May"
},
{
"PAY_YEAR": "2014",
"PAY_MONTH": "June"
},
{
"PAY_YEAR": "2014",
"PAY_MONTH": "July"
},
{
"PAY_YEAR": "2014",
"PAY_MONTH": "November"
},
{
"PAY_YEAR": "2014",
"PAY_MONTH": "December"
},
{
"PAY_YEAR": "2015",
"PAY_MONTH": "January"
},
{
"PAY_YEAR": "2015",
"PAY_MONTH": "February"
},
{
"PAY_YEAR": "2015",
"PAY_MONTH": "March"
},
{
"PAY_YEAR": "2015",
"PAY_MONTH": "April"
},
{
"PAY_YEAR": "2015",
"PAY_MONTH": "May"
},
{
"PAY_YEAR": "2015",
"PAY_MONTH": "June"
},
{
"PAY_YEAR": "2015",
"PAY_MONTH": "July"
},
{
"PAY_YEAR": "2015",
"PAY_MONTH": "August"
},
{
"PAY_YEAR": "2015",
"PAY_MONTH": "September"
},
{
"PAY_YEAR": "2015",
"PAY_MONTH": "October"
},
{
"PAY_YEAR": "2015",
"PAY_MONTH": "November"
},
{
"PAY_YEAR": "2015",
"PAY_MONTH": "December"
}
]
I dont want this kind of json.
i want like this image
my static json code is below:
<script type="text/javascript">
$(document).ready(function(){
// tree data
var data = [{
id: "0",
text: "2017",
data: {},
children: [
{id: "1", text: "January", data: {Action: '|'}},
{id: "2", text: "February", data: {Action: '|'}},
{id: "3", text: "March", data: {Action: '|'}},
{id: "4", text: "April", data: {Action: '|'}},
{id: "5", text: "May", data: {Action: '|'}},
{id: "6", text: "June", data: {Action: '|'}},
{id: "7", text: "July", data: {Action: '|'}},
{id: "8", text: "August", data: {Action: '|'}},
{id: "9", text: "September", data: {Action: '|'}},
{id: "10", text: "October", data: {Action: '|'}},
{id: "11", text: "November", data: {Action: '|'}},
{id: "12", text: "December", data: {Action: '|'}}
],
'state': {'opened': false},
}];
// load jstree
$("div#jstree").jstree({
plugins: ["table","dnd","contextmenu"],
core: {
data: data,
check_callback: true
},
// configure tree table
table: {
columns: [
{width: 200, header: "Year"},
{width: 150, value: "Action", header: "Action", format: function(v) {if (v){ return 'Print | Delete' }}},
],
resizable: true,
draggable: true,
contextmenu: true,
width: 400,
height: 300
}
});
});
</script>
please help me to get this kind of data with dynamic json.i tried lot but dont get any idea. I want nested json as you can see.

Try this:
<?php
include 'conn.php';
$year= array();
$sql = mysqli_query($conn,'SELECT SALARY_SLIP_ID,ORG_ID,EMPLOYEE_ID,PAY_MONTH,PAY_YEAR FROM india_salary_slip_details where EMPLOYEE_ID = 31');
while ($row = mysqli_fetch_array($sql ,MYSQLI_ASSOC))
{
if( !isset( $year[ $row['PAY_YEAR'] ] ) ) {
$year[ $row['PAY_YEAR'] ] = array();
}
if( !isset( $year[ $row['PAY_YEAR'] ][ $row['PAY_MONTH'] ] ) ) {
$year[ $row['PAY_YEAR'] ][ $row['PAY_MONTH'] ] = array();
}
}
echo json_encode($year);
?>

Related

How To Read Arrays In API Using Ajax And Jquery

I am creating a ticket reservation system. So , in this system I used API to request and get(response) data. But , when I got the response from API , it contains arrays of arrays.
{
"data": [
{
"type": "flight-offer",
"id": "1529553187230--523715719",
"offerItems": [
{
"services": [
{
"segments": [
{
"flightSegment": {
"departure": {
"iataCode": "CMB",
"at": "2018-07-02T03:15:00+05:30"
},
"arrival": {
"iataCode": "DOH",
"at": "2018-07-02T05:50:00+03:00"
},
"carrierCode": "BA",
"number": "6369",
"aircraft": {
"code": "77W"
},
"operating": {
"carrierCode": "QR",
"number": "6369"
},
"duration": "0DT5H5M"
},
"pricingDetailPerAdult": {
"travelClass": "ECONOMY",
"fareClass": "N",
"availability": 9,
"fareBasis": "NLRCAS"
}
},
{
"flightSegment": {
"departure": {
"iataCode": "DOH",
"at": "2018-07-02T06:35:00+03:00"
},
"arrival": {
"iataCode": "LHR",
"terminal": "4",
"at": "2018-07-02T12:00:00+01:00"
},
"carrierCode": "BA",
"number": "7007",
"aircraft": {
"code": "77W"
},
"operating": {
"carrierCode": "QR",
"number": "7007"
},
"duration": "0DT7H25M"
},
"pricingDetailPerAdult": {
"travelClass": "ECONOMY",
"fareClass": "N",
"availability": 9,
"fareBasis": "NLRCAS"
}
},
{
"flightSegment": {
"departure": {
"iataCode": "LHR",
"terminal": "2",
"at": "2018-07-02T14:15:00+01:00"
},
"arrival": {
"iataCode": "DUB",
"terminal": "2",
"at": "2018-07-02T15:40:00+01:00"
},
"carrierCode": "BA",
"number": "5965",
"aircraft": {
"code": "320"
},
"operating": {
"carrierCode": "EI",
"number": "5965"
},
"duration": "0DT1H25M"
},
"pricingDetailPerAdult": {
"travelClass": "ECONOMY",
"fareClass": "N",
"availability": 9,
"fareBasis": "NLRCAS"
}
}
]
},
{
"segments": [
{
"flightSegment": {
"departure": {
"iataCode": "DUB",
"terminal": "2",
"at": "2018-07-20T18:00:00+01:00"
},
"arrival": {
"iataCode": "LHR",
"terminal": "2",
"at": "2018-07-20T19:20:00+01:00"
},
"carrierCode": "BA",
"number": "5978",
"aircraft": {
"code": "320"
},
"operating": {
"carrierCode": "EI",
"number": "5978"
},
"duration": "0DT1H20M"
},
"pricingDetailPerAdult": {
"travelClass": "ECONOMY",
"fareClass": "S",
"availability": 9,
"fareBasis": "SLRCAS"
}
},
{
"flightSegment": {
"departure": {
"iataCode": "LHR",
"terminal": "4",
"at": "2018-07-20T21:55:00+01:00"
},
"arrival": {
"iataCode": "DOH",
"at": "2018-07-21T06:40:00+03:00"
},
"carrierCode": "BA",
"number": "7014",
"aircraft": {
"code": "359"
},
"operating": {
"carrierCode": "QR",
"number": "7014"
},
"duration": "0DT6H45M"
},
"pricingDetailPerAdult": {
"travelClass": "ECONOMY",
"fareClass": "S",
"availability": 9,
"fareBasis": "SLRCAS"
}
},
{
"flightSegment": {
"departure": {
"iataCode": "DOH",
"at": "2018-07-21T07:35:00+03:00"
},
"arrival": {
"iataCode": "CMB",
"at": "2018-07-21T15:20:00+05:30"
},
"carrierCode": "BA",
"number": "6366",
"aircraft": {
"code": "77W"
},
"operating": {
"carrierCode": "QR",
"number": "6366"
},
"duration": "0DT5H15M"
},
"pricingDetailPerAdult": {
"travelClass": "ECONOMY",
"fareClass": "S",
"availability": 9,
"fareBasis": "SLRCAS"
}
}
]
}
],
"price": {
"total": "837.46",
"totalTaxes": "464.46"
},
"pricePerAdult": {
"total": "837.46",
"totalTaxes": "464.46"
}
}
]
},
{
"type": "flight-offer",
"id": "1529553187230--1553108626",
"offerItems": [
{
"services": [
{
"segments": [
{
"flightSegment": {
"departure": {
"iataCode": "CMB",
"at": "2018-07-02T03:15:00+05:30"
},
"arrival": {
"iataCode": "DOH",
"at": "2018-07-02T05:50:00+03:00"
},
"carrierCode": "BA",
"number": "6369",
"aircraft": {
"code": "77W"
},
"operating": {
"carrierCode": "QR",
"number": "6369"
},
"duration": "0DT5H5M"
},
"pricingDetailPerAdult": {
"travelClass": "ECONOMY",
"fareClass": "N",
"availability": 9,
"fareBasis": "NLRCAS"
}
},
{
"flightSegment": {
"departure": {
"iataCode": "DOH",
"at": "2018-07-02T06:35:00+03:00"
},
"arrival": {
"iataCode": "LHR",
"terminal": "4",
"at": "2018-07-02T12:00:00+01:00"
},
"carrierCode": "BA",
"number": "7007",
"aircraft": {
"code": "77W"
},
"operating": {
"carrierCode": "QR",
"number": "7007"
},
"duration": "0DT7H25M"
},
"pricingDetailPerAdult": {
"travelClass": "ECONOMY",
"fareClass": "N",
"availability": 9,
"fareBasis": "NLRCAS"
}
},
{
"flightSegment": {
"departure": {
"iataCode": "LHR",
"terminal": "5",
"at": "2018-07-02T14:15:00+01:00"
},
"arrival": {
"iataCode": "DUB",
"terminal": "1",
"at": "2018-07-02T15:40:00+01:00"
},
"carrierCode": "BA",
"number": "830",
"aircraft": {
"code": "320"
},
"operating": {
"carrierCode": "BA",
"number": "830"
},
"duration": "0DT1H25M"
},
"pricingDetailPerAdult": {
"travelClass": "ECONOMY",
"fareClass": "S",
"availability": 9,
"fareBasis": "NLRCAS"
}
}
]
},
{
"segments": [
{
"flightSegment": {
"departure": {
"iataCode": "DUB",
"terminal": "1",
"at": "2018-07-20T16:30:00+01:00"
},
"arrival": {
"iataCode": "LHR",
"terminal": "5",
"at": "2018-07-20T18:00:00+01:00"
},
"carrierCode": "BA",
"number": "829",
"aircraft": {
"code": "321"
},
"operating": {
"carrierCode": "BA",
"number": "829"
},
"duration": "0DT1H30M"
},
"pricingDetailPerAdult": {
"travelClass": "ECONOMY",
"fareClass": "S",
"availability": 9,
"fareBasis": "SLRCAS"
}
},
{
"flightSegment": {
"departure": {
"iataCode": "LHR",
"terminal": "4",
"at": "2018-07-20T21:55:00+01:00"
},
"arrival": {
"iataCode": "DOH",
"at": "2018-07-21T06:40:00+03:00"
},
"carrierCode": "BA",
"number": "7014",
"aircraft": {
"code": "359"
},
"operating": {
"carrierCode": "QR",
"number": "7014"
},
"duration": "0DT6H45M"
},
"pricingDetailPerAdult": {
"travelClass": "ECONOMY",
"fareClass": "S",
"availability": 9,
"fareBasis": "SLRCAS"
}
},
{
"flightSegment": {
"departure": {
"iataCode": "DOH",
"at": "2018-07-21T07:35:00+03:00"
},
"arrival": {
"iataCode": "CMB",
"at": "2018-07-21T15:20:00+05:30"
},
"carrierCode": "BA",
"number": "6366",
"aircraft": {
"code": "77W"
},
"operating": {
"carrierCode": "QR",
"number": "6366"
},
"duration": "0DT5H15M"
},
"pricingDetailPerAdult": {
"travelClass": "ECONOMY",
"fareClass": "S",
"availability": 9,
"fareBasis": "SLRCAS"
}
}
]
}
],
"price": {
"total": "837.46",
"totalTaxes": "464.46"
},
"pricePerAdult": {
"total": "837.46",
"totalTaxes": "464.46"
}
}
]
}
Now I want to read and display these values in the view page. I mean I want to get and display type and id number. Then I tried below steps with laravel. I got all the details with
Console.log(data);.
But, couldn't get any thing into the view page. How can I get values to the view page ??
View page.
<form class="form-horizontal" method="POST" action="#" enctype="multipart/form-data" id="signupForm">
{{ csrf_field() }}
<div class="col-md-4 col-sm-12 hero-feature"> <!-- Start Of The Col Class -->
Origin City : <input type="text" class="form-control" name="origin" value="" id="origin"> <br>
</div>
<div class="col-md-4 col-sm-12 hero-feature"> <!-- Start Of The Col Class -->
Destination City : <input type="text" class="form-control" name="destination" value=""
id="destination"> <br>
</div>
<div class="col-md-4 col-sm-12 hero-feature"> <!-- Start Of The Col Class -->
Adults : <select name="st" class="form-control" id="adults">
#for ($i = 1; $i <= 9; $i++)
<option value="{{ $i }}">{{ $i }}</option>
#endfor
</select> <br>
</div>
<div class="col-md-4 col-sm-12 hero-feature"> <!-- Start Of The Col Class -->
Departure Date :<input class="form-control" type="text" name="departureDate" id="departureDate">
</div>
<div class="col-md-4 col-sm-12 hero-feature"> <!-- Start Of The Col Class -->
Return Date :<input class="form-control" type="text" name="returnDate" id="returnDate">
</div>
<div class="col-md-4 col-sm-12 hero-feature"> <!-- Start Of The Col Class -->
Access Token : <input type="text" class="form-control" name="bat" value="" id="bat"> <br>
</div>
Pull User Data
<p id="errorModal"></p> <br>
<div id="ghapidata" class="clearfix"></div>
</form>
<script type="text/javascript">
$(document).ready(function () {
$('#ghsubmitbtn').on('click', function(e){
var origin = $('#origin').val();
var destination = $('#destination').val();
var departureDate = $('#departureDate').val();
var returnDate = $('#returnDate').val();
var adults = $('#adults').val();
var bat = $('#bat').val();
var requri = 'https://test.api.amadeus.com/v1/shopping/flight-offers?origin=' + origin + '&destination=' + destination + '&departureDate=' + departureDate + '&returnDate=' + returnDate + '&adults=' + adults;
var repouri = 'https://test.api.amadeus.com/v1/shopping/flight-offers?origin=' + origin + '&destination=' + destination + '&departureDate=' + departureDate + '&returnDate=' + returnDate + '&adults=' + adults;
$.ajax({
url: 'https://test.api.amadeus.com/v1/shopping/flight-offers?origin=' + origin + '&destination=' + destination + '&departureDate=' + departureDate + '&returnDate=' + returnDate + '&adults=' + adults,
method: 'GET',
headers: {"Authorization": 'Bearer ' + bat},
success: function (data) {
console.log(data);
requestJSON(requri, function(JSON) {
// else we have a user and we display their info
var data = JSON.data;
var type = JSON.type;
var id = JSON.id;
var iataCode = JSON.iataCode;
var outhtml = '<h2>'+data+' <span class="smallname">(#'+type+')</span></h2>';
outhtml = outhtml + '<p>User Type: '+type+'</p></div>';
outhtml = outhtml + '<p>Id: '+id+' - IATA Code: '+iataCode+'<br></p></div>';
outhtml = outhtml + '<div class="repolist clearfix">';
var repositories;
$.getJSON(repouri, function(JSON){
repositories = JSON;
outputPageContent();
});
function outputPageContent() {
outhtml = outhtml + '<p><strong>Repos List:</strong></p> <ul>';
$.each(repositories, function(index) {
outhtml = outhtml + '<li>repositories[index].data.type</li>';
});
outhtml = outhtml + '</ul></div>';
$('#ghapidata').html(outhtml);
} // end outputPageContent()
}); // end requestJSON Ajax call
},
error: function (jQXHR) {
// If status code is 401, access token expired, so
// redirect the user to the login page
if (jQXHR.status == "401") {
$('#errorModal').modal('show');
}
else {
$('#divErrorText').text(jqXHR.responseText);
$('#divError').show('fade');
}
}
});
});
function requestJSON(url, callback) {
$.ajax({
url: url,
complete: function(xhr) {
callback.call(null, xhr.responseJSON);
}
});
}
});
</script>
Need to parse the response as JSON, then handle it from there:
JSON.parse(data)
$.getJSON(repouri, function(data){
repositories = JSON.parse(data);
data = repositories.data;
type = data.type;
id = data.id;
services = data.offerItems.services; // Referencing the sub objects within
outputPageContent();
});
See here:
http://jsfiddle.net/rhn9cweg/19/
gotta address the sections, can put it into a looping function to handle it a bit cleaner, but you need to parse the data to the function .
---- EDIT ----
to loop through each of the fields:
$.each(repositories, function (key, data) {
console.log(key);
$.each(data, function (index, data) {
console.log('index', data);
});
});
put that to a function and the call it on it self for using an if block to see if the item is an object. (call the function from within the function for a recurring check)
The field type, id are inside data in json array format so you can't read that directly using JSON.type or JSON.id
var data = JSON.data;
var type = data[0].type;
var id = data[0].id;
var iataCode = data[0].iataCode;
Please check browser console for error messages to debug your code

Reading PHP association array values in javascript

I try to generate simple chart from database values. I used AJAX to getting values from database and return this back to javascript. I would like generate chart from this values with canvas, but i don't know how can i read association PHP array in javascript.
#EDIT
AJAX request:
$.post({
type: "POST",
url: "execute.php",
data: {producer: producer, before: before, after: after, name: name},
dateType: 'json',
cache: false,
}).done(function(data) {
$("#xdebug").html(data);
});
PHP result looks like this:
$params = array();
foreach(array_unique($dates) as $date) {
$params[] = array("date" => $date, "sold" => sumOrders($date, $dbh), "scale" => sumOrders($date, $dbh) * 10);
}
echo json_encode($params);
I receive one this array in javascript
[{
"date": "2017-12-01",
"sold": "0",
"scale": 0
}, {
"date": "2017-12-02",
"sold": "0",
"scale": 0
}, {
"date": "2017-12-03",
"sold": "0",
"scale": 0
}, {
"date": "2017-12-04",
"sold": "0",
"scale": 0
}, {
"date": "2017-12-05",
"sold": "0",
"scale": 0
}, {
"date": "2017-12-06",
"sold": "0",
"scale": 0
}, {
"date": "2017-12-07",
"sold": "0",
"scale": 0
}, {
"date": "2017-12-08",
"sold": "0",
"scale": 0
}, {
"date": "2017-12-09",
"sold": "0",
"scale": 0
}, {
"date": "2017-12-10",
"sold": "0",
"scale": 0
}, {
"date": "2017-12-11",
"sold": "0",
"scale": 0
}, {
"date": "2017-12-12",
"sold": "0",
"scale": 0
}, {
"date": "2017-12-13",
"sold": "0",
"scale": 0
}]
How can i do that guys?
First of all there is a typo in your ajax code:
$.post({
type: "POST",
url: "execute.php",
data: {producer: producer, before: before, after: after, name: name},
dataType: 'json', //dataType not dateType
cache: false,
}).done(function(data) {
$("#xdebug").html(data);
});
now the response in data will be a json object instead, which you can easily use like:
.done(function(data) {
data.forEach(function (item){
console.log(item.date);
console.log(item.sold);
console.log(item.scale);
})
});
You are getting a JS array back from PHP, it's just like a normal JS array
$.post({
type: "POST",
url: "execute.php",
data: {producer: producer, before: before, after: after, name: name},
dataType: 'json',
cache: false,
}).done(function(data) {
// do something with your array, as in snippet after
});
Edit : typo in your attribute dateType => dataType
Exemple looping, but nobody knows except you what to do with it !
var data = [{"date":"2017-12-01","sold":"0","scale":0},{"date":"2017-12-02","sold":"0","scale":0},{"date":"2017-12-03","sold":"0","scale":0},{"date":"2017-12-04","sold":"0","scale":0},{"date":"2017-12-05","sold":"0","scale":0},{"date":"2017-12-06","sold":"0","scale":0},{"date":"2017-12-07","sold":"0","scale":0},{"date":"2017-12-08","sold":"0","scale":0},{"date":"2017-12-09","sold":"0","scale":0},{"date":"2017-12-10","sold":"0","scale":0},{"date":"2017-12-11","sold":"0","scale":0},{"date":"2017-12-12","sold":"0","scale":0},{"date":"2017-12-13","sold":"0","scale":0}];
for(var i in data){
console.log(data[i].date);
console.log(data[i].sold);
console.log(data[i].scale);
}

Fusionchart no chart only blank space

I am trying to create multi-series fusionchart using this guide.
I have JSON file $jsonEncodedData which is created from array $arrData and with new FusionCharts("msline", "myFirstChart" , 600, 300, "chart-1", "json", $jsonEncodedData) I am trying to covert it into the chart.
My code:
<?php
include("fusioncharts/fusioncharts.php");
?>
<html>
<head>
<script type="text/javascript" src="fusioncharts/js/fusioncharts.js"></script>
<script type="text/javascript" src="fusioncharts/js/themes/fusioncharts.theme.fint.js"></script>
</head>
<body>
<?php
$jsonEncodedData = json_encode($arrData);
$Chart = new FusionCharts("msline", "myFirstChart" , 600, 300, "chart-1", "json", $jsonEncodedData);
$Chart->render();
?>
<div id="chart-1">Fusion Charts will render here</div>
</body>
</html>
MY JSON file:
{
"chart":{
"caption":"Number of visitors last week",
"subCaption":"Bakersfield Central vs Los Angeles Topanga",
"captionFontSize":"14",
"subcaptionFontSize":"14",
"subcaptionFontBold":"0",
"paletteColors":"#0075c2,#1aaf5d,#FF5733,#33B5FF",
"bgcolor":"#ffffff",
"showBorder":"0",
"showShadow":"0",
"showCanvasBorder":"0",
"usePlotGradientColor":"0",
"legendBorderAlpha":"0",
"legendShadow":"0",
"showAxisLines":"0",
"showAlternateHGridColor":"0",
"divlineThickness":"1",
"divLineDashed":"1",
"divLineDashLen":"1",
"xAxisName":"Day",
"showValues":"0"
},
"categories":{
"category":[
{
"label":"N.12\/02"
},
{
"label":"Pn.13\/02"
},
{
"label":"Wt.14\/02"
},
{
"label":"\u015ar.15\/02"
},
{
"label":"Cz.16\/02"
},
{
"label":"Pt.17\/02"
},
{
"label":"So.18\/02"
}
]
},
"dataset":[
{
"seriesname":"IRDN",
"data":[
{
"value":"142.59"
},
{
"value":"174.88"
},
{
"value":"176.97"
},
{
"value":"182.48"
},
{
"value":"160.15"
},
{
"value":"160.72"
},
{
"value":"165.47"
}
]
},
{
"seriesname":"SIRDN",
"data":[
{
"value":"148.81"
},
{
"value":"197.29"
},
{
"value":"202.27"
},
{
"value":"211.93"
},
{
"value":"177.87"
},
{
"value":"179.37"
},
{
"value":"177.69"
}
]
},
{
"seriesname":"IRDN24",
"data":[
{
"value":"140.31"
},
{
"value":"174.50"
},
{
"value":"180.38"
},
{
"value":"187.70"
},
{
"value":"161.91"
},
{
"value":"161.62"
},
{
"value":"160.98"
}
]
},
{
"seriesname":"IRDN 8.22",
"data":[
{
"value":"147.33"
},
{
"value":"197.02"
},
{
"value":"202.21"
},
{
"value":"211.28"
},
{
"value":"178.11"
},
{
"value":"179.32"
},
{
"value":"176.31"
}
]
}
]
}
Eventhough it looks correct chart doesn't work (I got blank space without any errors, even text where the graph should appear <div id="chart-1">Fusion Charts will render here</div> disappears.
I have checked debugger and my proces stops on step 9 out of 12 http://www.fusioncharts.com/dev/api/fusioncharts/namespaces/debugger.html:
#1 [FusionCharts] fired "ready" event.
#2 [myChart] fired "beforeinitialize" event.
#3 [myChart] fired "beforedataupdate" event.
#4 [myChart] fired "dataupdated" event.
#5 [myChart] fired "initialized" event.
#6 [myChart] fired "beforerender" event.
#7 [myChart] fired "internal.loaded" event.
#8 [myChart] fired "internal.drawstart" event.
#9 [myChart] fired "dataloaded" event.
What can be a reason for that?
EDIT Thanks to #uom-pgregorio I have found my mistake.
In JSON 'category' should be in aditional []:
"categories": [{
"category": [{
"label": "Mon"
}, {
"label": "Tue"
}, {
"label": "Wed"
}, {
"label": "Thu"
}, {
"label": "Fri"
}, {
"label": "Sat"
}, {
"label": "Sun"
}]
}],
instead of:
"categories": {
"category": [{
"label": "Mon"
}, {
"label": "Tue"
}, {
"label": "Wed"
}, {
"label": "Thu"
}, {
"label": "Fri"
}, {
"label": "Sat"
}, {
"label": "Sun"
}]
},
Updating my answer because you provided a different guide.
From what I can see you forgot to do this step:
/**
* Convert the data in the `$actualData` array into a format that can be
* consumed by FusionCharts. The data for the chart should be in an array
* wherein each element of the array is a JSON object having the "label"
* and “value” as keys.
*/
$arrData['data'] = array();
// Iterate through the data in `$actualData` and insert in to the `$arrData` array.
foreach ($actualData as $key => $value) {
array_push($arrData['data'],
array(
'label' => $key,
'value' => $value
)
);
}
Update #1
I noticed you already have it hard-coded in your JSON but all you included is the value and no label. You're missing the label element.
Update #2
Basically you need to have your JSON in this format:
{
"chart": {
"caption": "Split of Visitors by Age Group",
"subCaption": "Last year",
"paletteColors": "#0075c2,#1aaf5d,#f2c500,#f45b00,#8e0000",
"bgColor": "#ffffff",
"showBorder": "0",
"use3DLighting": "0",
"showShadow": "0",
"enableSmartLabels": "0",
"startingAngle": "0",
"showPercentValues": "1",
"showPercentInTooltip": "0",
"decimals": "1",
"captionFontSize": "14",
"subcaptionFontSize": "14",
"subcaptionFontBold": "0",
"toolTipColor": "#ffffff",
"toolTipBorderThickness": "0",
"toolTipBgColor": "#000000",
"toolTipBgAlpha": "80",
"toolTipBorderRadius": "2",
"toolTipPadding": "5",
"showHoverEffect": "1",
"showLegend": "1",
"legendBgColor": "#ffffff",
"legendBorderAlpha": "0",
"legendShadow": "0",
"legendItemFontSize": "10",
"legendItemFontColor": "#666666",
"useDataPlotColorForLabels": "1"
},
"data": [
{
"label": "Teenage",
"value": "1250400"
},
{
"label": "Adult",
"value": "1463300"
},
{
"label": "Mid-age",
"value": "1050700"
},
{
"label": "Senior",
"value": "491000"
}
]
}

How to create a combo chart (bar and line) with fusioncharts using data from MySQL database?

I found this code online to do basically everything I was looking for except they are not using data from a MySQL database where as I am. Here is their code:
{
"chart": {
"caption": "Inventory by Product Categories",
"bgcolor": "FFFFFF",
"plotgradientcolor": "",
"showalternatehgridcolor": "0",
"showplotborder": "0",
"divlinecolor": "CCCCCC",
"showvalues": "0",
"showcanvasborder": "0",
"pyaxisname": "Cost of Inventory",
"syaxisname": "Units in Inventory",
"numberprefix": "$",
"labeldisplay": "STAGGER",
"slantlabels": "1",
"canvasborderalpha": "0",
"legendshadow": "0",
"legendborderalpha": "0",
"showborder": "0"
},
"categories": [
{
"category": [
{
"label": "Seafood",
"labelPadding": 0
},
{
"label": "Beverages",
"labelPadding": 12
},
{
"label": "Condiments",
"labelPadding": 0
},
{
"label": "Dairy Products",
"labelPadding": 12
},
{
"label": "Confections",
"labelPadding": 0
},
{
"label": "Meat/Poultry",
"labelPadding": 12
},
{
"label": "Grains/Cereals",
"labelPadding": 0
},
{
"label": "Produce",
"labelPadding": 12
}
]
}
],
"dataset": [
{
"seriesname": "Cost of Inventory",
"color": "008ee4",
"data": [
{
"value": "13510"
},
{
"value": "12480"
},
{
"value": "12024"
},
{
"value": "11271"
},
{
"value": "10392"
},
{
"value": "5729"
},
{
"value": "5594"
},
{
"value": "3549"
}
]
},
{
"seriesname": "Quantity",
"parentyaxis": "S",
"renderas": "Line",
"color": "f8bd19",
"data": [
{
"value": "701"
},
{
"value": "559"
},
{
"value": "507"
},
{
"value": "393"
},
{
"value": "386"
},
{
"value": "165"
},
{
"value": "258"
},
{
"value": "100"
}
]
}
]
}
This makes sense, but it's changing this JSON code to accept data from a database instead of hardcoding this that is difficult for me.
Here is the relevent part of my code:
<?php
$strQuery2 = "SELECT ScrapDate, SUM(Quantity) AS Quantity FROM Scrap WHERE Department = 'WE' GROUP BY ScrapDate ORDER BY ScrapDate";
// Execute the query, or else return the error message.
$result2 = $dbhandle->query($strQuery2) or exit("Error code ({$dbhandle->errno}): {$dbhandle->error}");
// If the query returns a valid response, prepare the JSON string
if ($result2) {
// The `$arrData` array holds the chart attributes and data
$arrData2 = array(
"chart" => array(
"caption" => "WE Last Week Scrap Quantity",
"paletteColors" => "#0075c2",
"bgColor" => "#ffffff",
"borderAlpha"=> "20",
"canvasBorderAlpha"=> "0",
"usePlotGradientColor"=> "0",
"plotBorderAlpha"=> "10",
"showXAxisLine"=> "1",
"xAxisLineColor" => "#999999",
"showValues"=> "0",
"divlineColor" => "#999999",
"divLineIsDashed" => "1",
"showAlternateHGridColor" => "0",
"xAxisName"=> "Day",
"yAxisName"=> "Quantity"
)
);
$arrData2["data"] = array();
// Push the data into the array
while($row2 = mysqli_fetch_array($result2)) {
array_push($arrData2["data"], array(
"label" => $row2["ScrapDate"],
"value" => $row2["Quantity"],
// "link" => "deptDrillDown.php?Department=".$row["Department"]
)
);
}
$jsonEncodedData2 = json_encode($arrData2);
$columnChart2 = new FusionCharts("column2D", "chart2" , 600, 300, "chart-2", "json", $jsonEncodedData2);
// Render the chart
$columnChart->render();
$columnChart2->render();
// Close the database connection
$dbhandle->close();
}
?>
As of right now, I can get data from the MySQL database and put it into a graph very easily. Now I want to add 1 more dataset, how do I do this?
To dynamically update the chart, following methods turns very useful:
getJSONData: Fetches chart data in the JSON format.
setJSONData: Sets chart data in the JSON data format
A sample implementation is shown in the below snippet. The chart is initially rendered as the default column2d chart. Once the Add Area button is clicked, an area dataset gets visually updated. Similarly on clicking the Add Line button to add a line dataset. The Reset button restores to original column only visual.
var visitChart,
areaBtn = document.getElementById('area'),
lineBtn = document.getElementById('line'),
resetBtn = document.getElementById('reset');
FusionCharts.ready(function() {
visitChart = new FusionCharts({
type: 'mscombi2d',
renderAt: 'chart-container',
width: '500',
height: '300',
dataFormat: 'json',
dataSource: {
"chart": {
"caption": "Actual Revenues, Targeted Revenues & Profits",
"subcaption": "Last year",
"xaxisname": "Month",
"yaxisname": "Amount (In USD)",
"numberprefix": "$",
"theme": "fint"
},
"categories": [{
"category": [{
"label": "Jan"
}, {
"label": "Feb"
}, {
"label": "Mar"
}, {
"label": "Apr"
}, {
"label": "May"
}, {
"label": "Jun"
}, {
"label": "Jul"
}, {
"label": "Aug"
}, {
"label": "Sep"
}, {
"label": "Oct"
}, {
"label": "Nov"
}, {
"label": "Dec"
}]
}],
"dataset": [{
"seriesname": "Actual Revenue",
"data": [{
"value": "16000"
}, {
"value": "20000"
}, {
"value": "18000"
}, {
"value": "19000"
}, {
"value": "15000"
}, {
"value": "21000"
}, {
"value": "16000"
}, {
"value": "20000"
}, {
"value": "17000"
}, {
"value": "25000"
}, {
"value": "19000"
}, {
"value": "23000"
}]
}]
}
}).render();
});
areaBtn.addEventListener('click', function() {
var dataset,
json = visitChart.getJSONData();
if (!(dataset = json.dataset)) {
dataset = json.dataset = [];
}
dataset.push({
"seriesname": "Profit",
"renderas": "area",
"showvalues": "0",
"data": [{
"value": "4000"
}, {
"value": "5000"
}, {
"value": "3000"
}, {
"value": "4000"
}, {
"value": "1000"
}, {
"value": "7000"
}, {
"value": "1000"
}, {
"value": "4000"
}, {
"value": "1000"
}, {
"value": "8000"
}, {
"value": "2000"
}, {
"value": "7000"
}]
});
visitChart.setJSONData(json);
areaBtn.disabled = true;
});
lineBtn.addEventListener('click', function() {
var dataset,
json = visitChart.getJSONData();
if (!(dataset = json.dataset)) {
dataset = json.dataset = [];
}
dataset.push({
"seriesname": "Projected Revenue",
"renderas": "line",
"showvalues": "0",
"data": [{
"value": "15000"
}, {
"value": "16000"
}, {
"value": "17000"
}, {
"value": "18000"
}, {
"value": "19000"
}, {
"value": "19000"
}, {
"value": "19000"
}, {
"value": "19000"
}, {
"value": "20000"
}, {
"value": "21000"
}, {
"value": "22000"
}, {
"value": "23000"
}]
});
visitChart.setJSONData(json);
lineBtn.disabled = true;
});
resetBtn.addEventListener('click', function() {
var dataset,
len,
json = visitChart.getJSONData();
if (!(dataset = json.dataset)) {
dataset = json.dataset = [];
}
if ((len = dataset.length) > 1) {
dataset.splice(1, len - 1);
}
visitChart.setJSONData(json);
areaBtn.disabled = false;
lineBtn.disabled = false;
});
<script src="http://static.fusioncharts.com/code/latest/fusioncharts.js"></script>
<script src="http://static.fusioncharts.com/code/latest/themes/fusioncharts.theme.fint.js"></script>
<button id='area'>Add Area</button>
<button id='line'>Add Line</button>
<button id='reset'>Reset</button>
<span id="chart-container">FusionCharts XT will load here!</span>
The data getting appended might be fetched from a database in a similar manner stated above.

DataTable AJAX source

I need to load a datatable from an AJAX source. My PHP script returns a JSON output in this form:
{
"SiteID": "61",
"SiteRef": "MI Swaco, Pocra Quay (Elect 910)",
"SupplierID": "1",
"StartDate": "2013-06-01 00:00:00.000",
"EndDate": "2014-05-31 00:00:00.000",
"Voltage": "LV"
},
{
"SiteID": "8",
"SiteRef": "UK Training Centre, (Elect 318)",
"SupplierID": "1",
"StartDate": "2013-07-01 00:00:00.000",
"EndDate": "2014-06-30 00:00:00.000",
"Voltage": "LV"
},
{
"SiteID": "115",
"SiteRef": "Smith Int, Bruce Fac (Gas 102)",
"SupplierID": "31",
"StartDate": "2013-08-01 00:00:00.000",
"EndDate": "2014-07-30 00:00:00.000",
"Voltage": "LV"
}
I have validated it via JSONLint and it says it is a valid JSON output. However when I use it for datatable it says invalid json output. This is how I am interfacing it with dataTable:
$(function() {
//$('#termTable').dataTable().makeEditable();
$('#termTable').dataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "terminateContractList.php"
},
"columns": [
{"data": "SiteID"},
{"data": "SiteRef"},
{"data": "SupplierID"},
{"data": "StartDate"},
{"data": "EndDate"},
{"data": "Volatage"}
]
});
});
Please correct the spelling of Voltage in your code.
$( function(){
//$('#termTable').dataTable().makeEditable();
$('#termTable').dataTable( {
"processing": true,
"serverSide": true,
"ajax": {
"url": "terminateContractList.php"
},
"columns": [
{ "data": "SiteID" },
{ "data": "SiteRef" },
{ "data": "SupplierID" },
{ "data": "StartDate" },
{ "data": "EndDate" },
{ "data": "Voltage" }
]
} );
});
"Voltage" in the JSON data won't match the "Volatage" column in your dataTable

Categories