kendo-ui grid date format from MySQL sql query - php

I have looked here for similar queries, and none quite answer my question, either in its entirety, or in a fashion I can understand.
I retrieve a string value from a MySQL database representing a datetime, i.e. "03 Oct, 2013 05:30:45PM" is represented as "20131003173045" in the database. This value is presented in a "Last Login" column in a Kendo Grid as a date. This is all contained within a PHP-oriented webpage using the MVC framework.
Previously I applied a date format in the SQL query to change the string from "20131003173045" to "03 Oct, 2013 05:30:45PM", but this gets presented in the KendoGrid as a string, meaning November Dates can appear before October dates, April dates come up first etc. This understandably is not the desired function, especially when trying to sort by this column.
Sample Code for the page rendering the KendoGrid:
<div class="div1">
<div>
<table id="listGrid"></table>
</div>
</div>
<script>
$(function() {
$("#grid").kendoGrid({
scrollable: false,
groupable: false,
sortable: {
mode: "multiple"
},
resizable: true,
pageable: true,
dataSource:
{
transport:
{
read: {
url: "<?= $site_url ?>Settings/Users/List",
dataType: "json"
},
parameterMap: function (model, operation) {
if (operation == "read") {
return model;
}
else if(model) {
return { "json" : kendo.stringify(model) };
}
else
return "";
}
},
pageSize: 20,
serverPaging: true,
serverSorting: true,
sort: { field: "LastLogin", dir: "desc" },
serverGrouping: true,
serverAggregates: false,
schema: {
total: "total",
data: "data",
groups: "groups"
}
},
toolbar: [ { title: "", template:'<a class="k-button k-button-icontext k-grid-add" href="<?= $site_url ?>Settings/Users/Add/">Add New User</a>' }],
columns: [
//{field: "Id", width: "40px"},
{field: "UserName", title: "Alias", width: "160px"},
{field: "ForeName", title: "Forename", width: "100px"},
{field: "SurName", title: "Surname", width: "160px"},
{field: "Initials", width: "80px"},
{field: "CrmId", title: "CRM ID", width: "100px"},
{field: "Dept", title: "Department", width: "100px"},
{field: "Position"},
// Below is the field in question
{field: "LastLogin", title: "Last Login", width: "160px"},
{field: "BlockedStatus", title: "Status", width: "90px"},
{ title: "", template:'<a class="k-button k-button-icontext k-grid-edit" href="<?= $site_url ?>Settings/Users/Update/#: Id #">Edit</a>' }
]
});
});
</script>
I've looked at the kendo.parseDate and kendo.toString, and combining the two, but can't seem to get anything to work; I either get "null" or "20131003173045", or the page doesn't load.
I can't change the database data, I can only format it as part of the SQL query, which is what I was doing initially.
I need the whole "20131003173045" string to become "03 Oct, 2013 05:30:45PM", and still be ordered in proper chronological order - how can I do this, and if the kendo.parseDate and kendo.toString are the correct tools to use, what am I doing wrong?

What I suggest is implement a schema.parse function that converts that MySQL format to a Date object and then use columns.format for formatting it.
The Schema would be:
schema : {
data : "data",
total : "total",
groups: "groups",
parse : function (d) {
$.each(d.data, function (idx, elem) {
elem.LastLogin = kendo.parseDate(elem.LastLogin, "yyyyMMddHHmmss");
});
return d;
}
}
Now, the columns definition for printing the date would define a format that is the one that you want.
{field: "LastLogin", title: "Last Login", width: "160px", format: "{0:dd MMM, yyyy hh:mm:sstt}" }},

Related

Count number of condidates based on country and view them in JvectorMap legend

I am using JvectorMap to show the Candidates Geographical details based on the number of candidates from a country. Like: i want to show the number of candidates from USA and same for other countries.
Example: USA, 5 Candidates
But it doesn't work. Instead it show 0 Candidates.
Therefore, my question is how to make JvectorMap to take the number of candidates based on country and display it in the map.
Column name for user: CandidatesName
Column name for country: Country
This is my code that i developed based on documentation of JvectorMap, but it is not working.
$("#world-map").vectorMap({
map: "world_mill",
backgroundColor: "#ffffff",
zoomOnScroll: false,
hoverOpacity: 0.7,
hoverColor: false,
regionStyle: {
initial: {
fill: "#e1e1e1",
stroke: "none",
"stroke-width": 0,
"stroke-opacity": 1
},
hover: {
"fill-opacity": 0.8
},
selected: {
fill: "#8dc859"
},
selectedHover: {
}
},
series: {
regions: [{
values: mapData,
scale: ["#6fc4fe", "#2980b9"],
normalizeFunction: "polynomial"
}]
},
onRegionTipShow: function(e, el, code)
{
el.html(el.html() + " (" + ((typeof mapData[code] == "undefined") ? "0" : mapData[code]) + " Candidates)");
}
});
This is the div where i display the map.
<div id="world-map" style="width: 100%; height: 400px;"></div>
Thanks in advance and looking forward to an answer. :)

Store numbers with '0' as prefix

I dont know how to tell but i still dont get it right. This is my code :
Ext.define("PL.view.list.listOnly", {
extend: 'Ext.form.Panel',
alias: 'widget.listlistonly',
config:{
fullscreen: true,
title: 'Master barang',
items:[{
xtype : 'panel',
layout: {
type: 'fit',
align : 'stretch',
pack : 'start',
},
defaults: {
allowBlank: true,
msgTarget: 'side',
labelWidth: 60,
margin: '5 5 5 5',
},
items:[{
xtype:'list',
height: '100%',
masked: { xtype: 'loadmask',message: 'Loading...' },
scrollable: {
direction: 'vertical',
directionLock: true
},
store:{
fields: [{
name:'szName',
},{
name:'szProductID',
},{
name:'szBarcode',
}],
autoLoad: true,
pageSize: 20,
proxy: {
type: 'ajax',
url: 'store/product/loadData.php',
pageParam: 'param',
reader: {
type: 'json',
rootProperty: 'topics',
}
}
},
variableHeights: false,
useComponents: true,
itemTpl: '<div class="myButton">' +
'<input type="button" name="{szProductID}" value="Edit" ' +
'style="padding:3px;">' +
'</div>' +
'<div class="myContent">'+
'<div>PLU : <b>{szProductID}</b>, Barcode: <b>{szBarcode}</b></b></div>' +
'<div>Nama: <b>{szName}</b></div>' +
'</div>',
}]
}],
scrollable : false,
},
});
And this is what i get from json :
{"topics": [{
"szProductID": 1001,
"szBarcode": 002,
"szName": "STANDARD BLACK"
},{
"szProductID": 1100420020479,
"szBarcode": 1100420020479,
"szName": "STANDARD BLUE"
}],
"totalCount": 2}
As you can see, there is a '002' (szBarcode field), and this is my problem. The list only show '2' instead of '002'. This should show '002' as szBarcode but i dont know how to fix this.
Any help would appreciate
The problem is that barcode: 002 and barcode: 2 mean exactly the same in JSON format. Prepended zeros for numbers just don't count.
There are about four different things you can possibly do.
If you can access the server code, you can change it to send you the barcode field as a string (barcode:"002").
If your barcode ALWAYS has a certain length (say 13), you can work with the number you have, and pad it to the required length again. Please be aware that after a certain length, there are precision issues because numbers are stored in fixed-length memory, while a string's memory always is as long as needed. Sample conversion code:
name:'barcode',
convert:function(value) {
var str = value.toString(),
pad = "0000000000000"; // expand to length of your number
return pad.substring(0, pad.length - str.length) + str);
}
(Bonus: This code does not break when someone does (1) afterwards...)
If you have no other barcode fields in your JSON, you could use a regular expression to add the necessary quotes to the JSON client-side before deserialization.
You could override ExtJS's default JSON serialization/deserialization code. Please note that this is not as easy as it sounds and may have quite some side effects. This is the only suitable way if you want to send barcode as zero-padded JSON numbers back to the server as well.

display a weekly Highcharts graph from php and mysql

I am trying to get a chart to display using Highcharts. I am pulling data from a mysql db with php and creating arrays of data and inserting them into the Highcharts Jquery.
I need to display the data in this format (not a graphical representation):
mon = 0
tues = 4
wed = 2
thu = 0
fri = 4
sat = 20
sun = 45
With Monday always being first and Sunday last.
But my data is pulled from the DB using a date range and I may only get an array from the database that looks like this:
Array
(
[0] => Array
(
[TotalClicksPerDay] => 35
[weekDay] => 4 (which is my case is Thurs)
)
}
So in this case would need to display:
(the TotalClicksPerDay is the important bit)
mon = 0
tues = 0
wed = 0
thu = 35
fri = 0
sat = 0
sun = 0
How would I add the array values to Highchart and still get the days of the week to show and position 'thu's' value in the correct place?
has anyone done anything similiar? Can you point me on the right direction?
I don't even know how to start.
Here is my highcharts Jquery just so you can see how I am using the arrays:
jQuery(document).ready(function($) {
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: '$type'
},
subtitle: {
text: 'Xbox landscape'
},
xAxis: {
categories:
$categoryGraph //php array
,labels: {
rotation: 0,
align: 'center',
x: 0,
y: 20,
style: {
fontSize: '8px',
fontFamily: 'Verdana, sans-serif'
}
}
},
yAxis: {
min: 0,
title: {
text: 'Clicks'
}
},
legend: {
enabled: false
}, /*{
layout: 'Vertical',
backgroundColor: '#FFFFFF',
align: 'left',
verticalAlign: 'top',
x: 0,
y: 30,
floating: false,
shadow: true
},*/
tooltip: {
formatter: function() {
return ''+
this.x +': '+ this.y +' Clicks';
}
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{name: '$type', data:[$clickTotalArray //php array }]
});
});
});
You are asking for how to parse your data into something that highcharts understands?
Well, the main dynamic options that you want to set correctly would be the xAxis.categories and the series.data, which you seem to have figured out already.
categories
needs to be an array of strings, nothing more or nothing less will be accepted.
eg:- categories=['Mon','Tue','Wed']
data
needs to be an array of array or array of objects or array of values. See documentation for more details
Since your data is mostly simple values, with the xValue being a string and hence falling into categories, your data object needs to be an array of numbers.
eg:- data=[100,200,300]
So now we have the final form of how your data would look like, we need to parse the available data structure/object graph into this form. You have an option to either do this in PHP or JavaScript.
This is how you can do it in javascript, make sure to do this before calling the Highchart constructor, and use the derived objects while setting the options.
var superData = [{
propertyA: 'A',
propertyB: 10
}, {
propertyA: 'B',
propertyB: 15
}, {
propertyA: 'C',
propertyB: 1
}];
var seriesData = [],
categories = [];
for (var i = 0; i < superData.length; i++) {
//you may want to do a parseInt/parseFloat it this value is a string
seriesData.push(superData[i].propertyB);
categories.push(superData[i].propertyA);
}
...
xAxis: {
categories: categories
},
series: [{
name: 'serie',
type: 'column',
data: seriesData
}]
...
Parsing complex JSON into highchart form | Highchart & Highstock # jsFiddle
Refer convert mysql resultset into a (name, data) object to be fed into HighCharts to see how a similar thing can be done in PHP

can't add data to jqGrid from php within json format

Hello StackOverFlow nation . I'm trying to add information to jqGrid , which is retrieved from MySQL database. I've two files => index.html and data.php (both in the same directory)
index.html source =>
<script type="text/javascript">
$(function(){
$("#jqGrid_tb").jqGrid({
url: "data.php",
datatype: "json",
sortable: true,
height: "auto",
colNames: ["Name","Surname","Birth Year","Famous Film"],
colModel: [
{name: "name", index: "name", width: "150"},
{name: "surname", index: "surname", width: "150"},
{name: "b_year", index: "year", width: "150"},
{name: "film", index: "film", width: "200"}
],
rowNum: 5,
rowList: [5,10,15],
viewrecords: true,
pager: $("#pager"),
caption: "Famous Actors",
}).navGrid("#pager");
});
</script>
<div id="grid">
<table id="jqGrid_tb"></table>
<div id="pager"></div>
</div>
data.php source =>
include ("JSON.php");
$json = new Services_JSON();
$con = new mysqli("host","user","pswd","db");
if (!$con->connect_errno){
if ($r = $con->query("SELECT * FROM actors")){
while ($row = $r->fetch_assoc()){
$info[] = array(
"name" => $row[name],
"surname" => $row[surname],
"b_year" => $row[b_year],
"film" => $row[film],
);
}
$r->free();
}
}
echo $json->encode($info);
if (isset($con)){
$con->close();
}
jqGrid is shown without any information in index.html file , also when opening data.php file information is successfully encoded into JSON format , whats wrong I can't understand . Please help , thanks ...
Your response format is wrong. You can go to jqGrid Demos page where you will find a sample for PHP/MySQL after expanding Loading Data and then choosing JSON Data.
The proper format of data should look like this:
{
"total": "1",
"page": "1",
"records": "2",
"rows": [
{ "name": "Robert", "surname": "De Niro", "b_year": "1943", "film": "Once Upon A Time In America" },
{ "name": "Al", "surname": "Pacino", "b_year":"1971", "film": "Scent Of A Woman"}
]
}
Where:
total --> total count of pages
page --> current page number
records --> total count of records
rows --> the rows of data
Also if you want rows to be objects, you need to disable repeatitems in jqGrid jsonReader options:
$("#jqGrid_tb").jqGrid({
...
jsonReader: { repeatitems: false }
});
It is also adviced for rows to have unique id for later reference.
You should include
jsonReader: {
repeatitems: false,
root: function (obj) { return obj; },
page: function (obj) { return 1; },
total: function (obj) { return 1; },
records: function (obj) { return obj.length; }
}
as additional option of jqGrid is you don't want to change format of input data. Moreover you should specify which values should assign jqGrid as id attribute of the row. You can include additional id property as additional property of every returned item or you can add key: true property to the column (in colModel) which contains unique values. For example if you can guarantied that the values from "name" are already unique then you can include key: true property in definition of "name" column.
Additionally you can consider to use loadonce: true option of jqGrid. In the case the full data of the grid will be loaded at once and the sorting, paging and searching (filtering) of data will be implemented by jqGrid on the client side without needs to implement some additional code on the server side. You should don't use the option in case of large number of rows (many hundred or many thousand rows) in the grid.

jqgrid json reader for geoJson

I have a PHP script that extract valid GeoJSON data from a database. Now I would like to prepare a grid view of these data with jqgrid, but I can't figure out the proper jsonReader for the javascript code.
This is my GeoJSON output:
{"type":"FeatureCollection",
"total":0,
"page":1,
"records":117,
"features":[
{"geometry":{"type":"Point","coordinates":[12.3,41.70052]},
"type":"Feature",
"properties":{
"data":"2006-02-22",
"specie":"S. coeruleoalba",
"localita":"Ostia",
"provincia":"Roma"
},"id":0},
{"geometry":{
"type":"Point","coordinates":[15.26667,40.0502]},
"type":"Feature",
"properties":{
"data":"2006-03-01",
"specie":"S. coeruleoalba",
"localita":"Golfo di Salerno",
"provincia":"Salerno"
},"id":1},
{"geometry":{"type":"Point","coordinates":[14.88333,40.56692]},
"type":"Feature",
"properties":{
"data":"2006-03-03",
"specie":"S. coeruleoalba",
"localita":"Battipaglia",
"provincia":"Salerno"
},"id":2}
]}
Using this reader my grid shows the right number of rows (117) and pages, but empty cells
jsonReader : {
root: "features",
page: "page",
total: "total",
records: "records",
repeatitems: false,
cell: "properties",
id: "id"
}
Can someone help me to write a working reader? Thanks in advance
Your main error is that you try to use cell: "properties", but cell property will be ignored in case of usage of repeatitems: false property.
You should just use
jsonReader: {
root: "features",
repeatitems: false
}
and then define jsonmap property for every column. For example you can use the following column definition:
colModel: [
{name: 'coordX', jsonmap:'geometry.coordinates.0', width: 75, sorttype: 'number',
formatter: 'number', formatoptions: {decimalPlaces: 5}},
{name: 'coordY', jsonmap:'geometry.coordinates.1', width: 75, sorttype: 'number',
formatter: 'number', formatoptions: {decimalPlaces: 5}},
{name: 'data', jsonmap:'properties.data', width: 90, align: 'center',
sorttype: 'date', datefmt: 'm/d/Y',
formatter: 'date', formatoptions: {newformat: 'm/d/Y'}},
{name: 'specie', jsonmap:'properties.specie', width: 100},
{name: 'localita', jsonmap:'properties.localita', width: 100},
{name: 'provincia', jsonmap:'properties.provincia', width: 80}
]
As the result you will be able to read your JSON data to the following grid:
(see the demo here). In your JSON data I changed only total value from 0 to 1 because it has no sense to have the total value less as the page value.

Categories