Aggregate data for months in chart.js - PHP, MySQL, JS - javascript

I'm newbie to js and data aggregating for charts and it would be great to know how to aggregate data in a chart collecting them for months. In the example I'm trying to sum the money data for each employee id for months but the result is always passed like singular queries.
Here it is my code in js:
$(document).ready(function() {
/**
* call the data.php file to fetch the result from db table.
*/
$.ajax({
url : "http://localhost:8888/site/function/data.php",
type : "GET",
success : function(data){
console.log(data);
var importo = {
TRCLRT76T08F704F : [],
NGLLSN80T03F839Y : []
};
var len = data.length;
for (var i = 0; i < len; i++) {
if (data[i].cf == "TRCLRT76T08F704F") {
importo.TRCLRT76T08F704F.push(data[i].importo);
}
else if (data[i].cf == "NGLLSN80T03F839Y") {
importo.NGLLSN80T03F839Y.push(data[i].importo);
}
}
//get canvas
var ctx = $("#line-chartcanvas");
var data = {
labels : ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"],
datasets : [
{
label : "TRCLRT76T08F704F importo",
data : importo.TRCLRT76T08F704F,
backgroundColor : "blue",
borderColor : "lightblue",
fill : false,
lineTension : 0,
pointRadius : 5
},
{
label : "NGLLSN80T03F839Y importo",
data : importo.NGLLSN80T03F839Y,
backgroundColor : "green",
borderColor : "lightgreen",
fill : false,
lineTension : 0,
pointRadius : 5
}
]
};
var options = {
title : {
display : true,
position : "top",
text : "Line Graph",
fontSize : 18,
fontColor : "#111"
},
legend : {
display : true,
position : "bottom"
}
};
var chart = new Chart( ctx, {
type : "line",
data : data,
options : options
} );
},
error : function(data) {
console.log(data);
}
});
Here it is the function to call the db in data.php
$query = sprintf("SELECT cf, mese, importo FROM table WHERE `anno` = '2017' AND `importo` > '0' ORDER BY stamp_start");
//execute query
$result = $mysqli->query($query);
//loop through the returned data
$data = array();
foreach ($result as $row) {
$data[] = $row;
}

Related

How to display all fields of a nested json in table format using Bootstrap

I want to write a utility which connects to a REST api downloads data in JSON format and then paints the data as nested tables using Bootstrap.
JSON Data -
[
{
"id" : "Id1",
"name" : "Name1",
"orders" : [{"orderId" : "o1", "size" : 34}, {"orderId" : "o2", "size" : 3}]
},
{
"id" : "Id2",
"name" : "Name2",
"orders" : [
{"orderId" : "o3", "size" : 5, "addresses" : [{"addressId" : "a1", "phone" : "1235"}, {"addressId" : "a2", "phone" : 555}]},
{"orderId" : "o4", "size" : 5, "addresses" : [{"addressId" : "a3", "phone" : "1235"}]}
]
}
]
I looked at the sub-table feature of Bootstrap, however it seems that it would need lot of custom code to get this working. Is there a better way to bind the json to table in a generic way?
Edit
After spending some time I was able to achieve this -
As you can see, I could get one level of nesting, however i just need to go one level deep. Any suggestions?
<script>
var $table = $('#table')
function buildTable($el, jsonData) {
var i; var j; var row
var columns = []
var data = []
if(!Array.isArray(jsonData) && jsonData.length == 0) {
return;
}
Object.keys(jsonData[0]).forEach( (k) => {
columns.push({
field: k,
title: k,
sortable: true
})
})
for(var j = 0; j < jsonData.length; j++) {
row = {}
Object.keys(jsonData[j]).forEach( (k) => {
row[k] = jsonData[j][k]
})
data.push(row)
}
$el.bootstrapTable({
columns: columns,
data: data,
detailFilter: function (index, row) {
console.log("detail filter " + Object.values(row))
for(var k in row) {
if(Array.isArray(row[k])){
return true;
}
}
return false;
},
onExpandRow: function (index, row, $detail) {
console.log("expand row keys " + Object.keys(row))
console.log("expand row vals " + Object.values(row))
var newRow = {};
for(var k in row) {
if(Array.isArray(row[k])){
alert('found ' + row[k])
newRow = row[k]
break
}
}
buildTable($detail.html('<table></table>').find('table'), newRow)
}
})
};
var mydata =
[
{
"id": 0,
"name": "test0",
"price": "$0",
"orders" :
[
{
"name" : "ABC",
"size" : 25,
"someList": [{"a":1, "b":2}, {"a":3, "b":4}]
},
{
"name" : "XYZ",
"size" : 50
}
]
}
/* {
"id": 1,
"name": "test1",
"price": "$1"
},
{
"id": 2,
"name": "test2",
"price": "$2",
"orders" : [{"name" : "def", "size": 45}]
}*/
];
$(function() {
buildTable($table, mydata)
})

How can I reference this data in this JSON file?

I am using d3.js's "d3.json(); function to reach out and fetch some data from a REST API.
The data comes back as this:
{
"offset" : 0,
"rows": [
{ "_id":
{ "$oid" : "1234567" },
"mockupData" : [ {
"Analysis" : "Test",
"Description" : "The Test indicates...",
"Data" : [
{ "Category" : "A",
"Statistic" : 0.15,
"Value" : 0.95 },
{ "Category" : "B",
"Statistic" : 0.65,
"Value" : 0.85 },
] } ] }
],
"total_rows" : 1 ,
"query" : {} ,
"millis" : 0
}
I am having an extremely difficult time drilling down in to the json to get what I want.
I'm attempting to set it up like this:
function generateChart(){
var chart;
var Category = [{key:"Stuff", values:[]}];
d3.json('http://url_that_returns_json/', function(error,data{
for(var key in data._SOMETHING_){
switch(key){
case "A":
Category[0] ["values"].push({"label":"Statistic","value""data.Category[key]});
... // same for B
})
// more graph logic
I appear to be missing some entire fragment of knowledge on this. Guidance? Help?
Thanks in advance.
Here is a fiddle I have implemented : https://jsfiddle.net/thatOneGuy/486mwb86/1/
First off, I set the data as a variable so I can use it later. So :
var data = {
"offset": 0,
"rows": [{
"_id": {
"$oid": "1234567"
}, ... //and so on
This is exactly the same as you using :
d3.json('http://url_that_returns_json/', function(error,data{
Both data variables are the same.
Then I got to the point you wanted to check, i.e the categories in the data attribute, like so :
var thisDataSet = data.rows[0].mockupData[0].Data;
As this is an array and not an object, I used a for loop to loop through :
for (var i = 0; i < thisDataSet.length; i++) {
And, in my opinion, you didn't need a switch statement as it looks like you just wanted to populate Category.values with the different categories. So I just pushed the current value of the category in the dataset to this Category.values :
Category[0]["values"].push({
"label": "Statistic",
"value": thisDataSet[i].Category //push category here
});
And that's it. Check the console log for output. Should work fine. Full function :
function generateChart() {
var chart;
var Category = [{
key: "Stuff",
values: []
}];
console.log(data.rows[0].mockupData[0].Data)
var thisDataSet = data.rows[0].mockupData[0].Data;
for (var i = 0; i < thisDataSet.length; i++) {
//for (var key in data.rows[0].mockupData[0].Data) {
console.log(thisDataSet[i])
Category[0]["values"].push({
"label": "Statistic",
"value": thisDataSet[i].Category
});
}
console.log(Category)
}

reload tableview on click of picker element with updated data in titanium

I have a json response like this which is coming from API call.
`{
"id": "7",
"issue_title": "Apr - May 2015",
"issue_no": "Issue 1.4",
"cover_image_url": "http://www.link.org/apr--may-2015-7.jpg",
"synopsis_pdf_url": "",
"advertisers_pdf_url": "",
"issue_date": "01-04-2015",
"issue_year": "2015"
},
{
"id": "3",
"issue_title": "Feb-Mar 2015",
"issue_no": "Issue 1.3",
"cover_image_url": "http://www.link.org/febmar-2015-3.jpg",
"synopsis_pdf_url": "http://www.link.org/febmar-2015-3.pdf",
"advertisers_pdf_url": "http://www.link.org/febmar-2015-3.pdf",
"issue_date": "01-02-2015",
"issue_year": "2015"
},
{
"id": "2",
"issue_title": "Dec 2014 - Jan 2015",
"issue_no": "Issue 1.2",
"cover_image_url": "http://www.link.org/dec-2014--jan-2015-2.jpg",
"synopsis_pdf_url": "",
"advertisers_pdf_url": "",
"issue_date": "01-12-2014",
"issue_year": "2014"
},
{
"id": "1",
"issue_title": "Oct - Nov 2014",
"issue_no": "Issue 1.1",
"cover_image_url": "http://www.link.org/oct--nov-2014-1.jpg",
"synopsis_pdf_url": "",
"advertisers_pdf_url": "",
"issue_date": "01-10-2014",
"issue_year": "2014"
}`
Now I am retreiving issue_year which I am displaying in picker.
I want if a user clicks on issue_year the table data should display only records which have same issue_year.
Like if 2014 is clicked from picker it should display only 3rd and 4th record.
Now from controller I am passing object which jsonResponse[i] in the picker when picker data is prepared so as to retreive the same in its click but I am getting undefined.
js code is as follows
function openpastIssues(e) {
var url = "http://example.com/api/past_year_issue.aspx";
var jsonResponse;
var response;
var data = [];
var pickerData = [];
var singleData = [];
var row;
var xhr = Ti.Network.createHTTPClient({
onload : function() {
// parse the retrieved data, turning it into a JavaScript object
Ti.API.info("From Past Issues (function): " + this.responseText);
jsonResponse = JSON.parse(this.responseText);
var rowHeight = 150;
// just pick the right height here
var imageRowIsFull = false;
var myImage;
var issuelbl;
var row = Ti.UI.createTableViewRow({
width : Ti.UI.SIZE,
height : Ti.UI.SIZE,
layout : "horizontal"
});
for (var i = 0; i < jsonResponse.length; i++) {
var tView = Ti.UI.createView({
width : Ti.UI.SIZE,
height : Ti.UI.SIZE,
left : "5%",
right : "5%",
top : "5",
bottom : "5",
backgroundColor : "#A9F5A9",
//backgroundColor : "black",
layout : "vertical"
});
issuelbl = Ti.UI.createLabel({
color : 'blue',
text : jsonResponse[i].issue_title,
height : "auto",
width : "auto",
left : "3%",
font : {
fontSize : 13
},
});
tView.add(issuelbl);
myImage = Ti.UI.createImageView({
width : 120,
//left : "5%",
//right : "5%",
top : "5",
//bottom:"5",
height : 150,
image : jsonResponse[i].cover_image_url,
obj : jsonResponse[i]
});
tView.add(myImage);
try {
myImage.addEventListener('click', function(e) {
Ti.API.info('Clicked data = ' + JSON.stringify(e.source.obj));
var jsonRes = e.source.obj;
Alloy.createController('singleissue', jsonRes);
});
} catch(e) {
}
row.add(tView);
//row.add(myImage);
imageRowIsFull = false;
if ((i + 1) % 2 == 0) {//this will add a new row every 2 items.
imageRowIsFull = true;
data.push(row);
row = Ti.UI.createTableViewRow({
width : Ti.UI.SIZE,
height : Ti.UI.SIZE,
layout : "horizontal",
filterCriteria :jsonResponse[i].issue_year
});
}
pickerData[i] = Ti.UI.createPickerRow({
title : jsonResponse[i].issue_year,
obj : jsonResponse[i]
});
}
if (!imageRowIsFull) {//do not forget to add the last row
data.push(row);
}
//table.setData(data); 
$.issueTable.setData(data);
$.picker.add(pickerData);
},
onerror : function(e) {
Ti.API.debug(e.error);
alert('error');
},
timeout : 5000
});
xhr.open("GET", url);
xhr.send();
}
$.picker.addEventListener('change', function(e) {
Ti.API.info('From picker ' + e.source.obj);
});
xml file
<Alloy>
<Window id="winpast" class="container" title="Past issues" onOpen="openpastIssues">
<View id="view2" width="Ti.UI.FILL" height="Ti.UI.FILL" backgroundColor="#A9F5A9" >
<View id="viewcheck1" >
<Label id="title" width="Ti.UI.SIZE" text="Past Issues" height="Ti.UI.SIZE" textAlign="Ti.UI.TEXT_ALIGNMENT_CENTER"></Label>
<ImageView id="menuImg" image="/images/menu.png" onClick="showsideBar" left="5"></ImageView>
<Picker id="picker" selectionIndicator="true" height="Ti.UI.SIZE" width="Ti.UI.SIZE" right="10">
</Picker>
</View>
<View id="tablePast" width="Ti.UI.FILL" height="Ti.UI.FILL" top="40">
<TableView id="issueTable" scrollable="true"></TableView>
</View>
<View id="viewBelow" width="150" height="Ti.UI.FILL" backgroundColor="#A9A5A9" left="-150" visible="false" top="40">
<TableView id="menuTable"></TableView>
</View>
</View>
</Window>
</Alloy>
Basically I want to display a records of particular year selected from picker.
Can anyone please help on this.
I have spent a lot of time on this.
You can make an NSMUtableArray and repopulate it depending on the values of "issue_year". You can use NSPredicate for sorting through your json

How to convert String to Array in MongoDB?

I'm stuck at the situation when the type of an object was changed.
How can I convert this:
{
"_id" : NumberLong(257),
"address" : "street Street, house 50, appartment 508, floor 5"
}
to this:
{
"_id" : NumberLong(257),
"userAddressList" : [{
"street" : "Street",
"house" : "50",
"building" : "",
"appartment " : NumberLong(508),
"entrance" : NumberLong(0),
"floor" : NumberLong(5),
"intercom" : ""
}]
}
using mongo shell?
I need to convert about 350 entries, hope it can be done by the script.
You could try this:
db.collection.find().forEach( function (x) {
lines = x.address.split(",");
obj = {};
userAddressList = [];
lines.forEach( function (address){
addressArray = address.replace(/^\s\s*/, '').replace(/\s\s*$/, '').split(" ");
obj[addressArray[0]] = !isNaN(parseInt(addressArray[1])) ? parseInt(addressArray[1]) : addressArray[1];
});
obj.building = "";
obj.intercom = "";
userAddressList.push(obj);
x.userAddressList = userAddressList; // convert field to string
db.collection.save(x);
});
you can use a foreach in the update like this
db.test.find( { } ).forEach( function (x) {
x.userAddressList = x.address.split(" ");
db.test.save(x);
});

On using php mongo execute command showing an error "exception: can't have . in field names", and error code : 16722

I am trying to run a set of java script and update command using by php mongo execute command:
$pSsId = '123456789';
$pUid = 14;
$pRowID = '6fce077519d838bb8ed401448dae6e3a';
$pKey = 'name';
$pValue = 'King Kobra';
$response = $db()->execute("
function(pSsid, pUid, pRowid, pKey, pValue){
udocs = db.VizSpreadsheet.findOne({'_id' : pSsid, 'data.uid' : pUid }).data;
posU = udocs.map(function(d) { return d.uid; }).indexOf(pUid);
posR = udocs[posU].rows.map(function(r) { return r.row_id; }).indexOf(pRowid);
var setCriteria = {};
setCriteria['_id'] = pSsid;
setCriteria['data.uid'] = pUid;
var setObject = {};
setObject['data.'+posU+'.'+'rows'+'.'+posR+'.'+pKey] = pValue;
db.VizSpreadsheet.update(
{
setCriteria
},
{
'$set': setObject
}
);
}", array($pSsId, $pUid, $pRowID, $pKey, $pValue));
But the result is error
Array ( [errmsg] => exception: can't have . in field names [data.1.rows.0.2#12#07337187ee7e48f92ed1689b22d7ed77] at src/mongo/shell/collection.js:155 [code] => 16722 [ok] => 0 )
The collection will look like this
"_id" : "123456789",
"data" : [
{
"uid" : 12,
"rows" : [
{
"row_id" : "8979afefedb42aa8c62e9baa83e35ba0",
"updated_by" : "12",
"updated_at" : "1428644989",
"name" : "AAAAAAAAAAA"
},
{
"row_id" : "7415f767c62a84173d1dcf82ad1d809d",
"updated_by" : "12",
"updated_at" : "1428644989",
"name" : "BBBBBBBBBBBBB"
}
]
},
{
"uid" : 14,
"rows" : [
{
"row_id" : "21b1120811cfe893486e9e9afbebb660",
"updated_by" : "12",
"updated_at" : 1428644989,
"name" : "CCCCCCCCCC"
},
{
"row_id" : "6fce077519d838bb8ed401448dae6e3a",
"updated_by" : "12",
"updated_at" : 1428644841,
"names" : "DDDDDDDDDDD"
}
]
}
What i am trying is to update "name" field of second element in "rows" array for "uid" = 14. The data is updated by '$set' method and specifying the element position which is find by javascript code.
The same code executed successfully in shell.
But in php it fails to detect the position operator.
As an error message says, you cannot use . (dots) within your data.
Try separate your 'subfields' with : for example:
setObject['data:'+posU+':'+'rows'+':'+posR+':'+pKey] = pValue;

Categories

Resources