Json Data not populating jqGrid - json

My jqGrid is not populating on-submitting my form in Asp.net MVC 4 ... I am want to find out why... I have an ajax method that returns this Json string and it is a Json string in the Network response browser...
"{\"total\":1,\"page\":1,\"records\":1,\"rows\":[{\"cell\":[\"\",\"342352857634\",\"test\",\"test\",\"5/8/2012 11:39:38 AM\",\"1\",\"\",\"1/1/0001 12:00:00 AM\",\"1/1/0001 12:00:00 AM\",\"1/1/0001 12:00:00 AM\"]}]}"
this is the function that does all of the Magic.
$('#SearchPatID').submit(function (event) {
//alert("What the motherFuck is going on here!");
debugger;
var theURL = this.action;
var type = this.methd;
event.preventDefault();
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
dataType: "json",
success: function (result) {
debugger;
bindData(result);
}
});
return false;
});
var bindData = function (result) {
debugger;
alert('Glad this is kind-of working!');
$("#list").setGridParam({
datatype: 'jsonstring',
datastr: result,
caption: 'Suck It!'
}).trigger("reloadGrid");
}
UPDATE... I chamged my bindData function to Just setGridParam. and reload... Still doesn't work, but I think I am on the right path finally... More updates below...
What Am I missing? I have my Json data, everything should be working out fine right?
UPDATE:
I realized I was sending in a JSON string and not necesarrily a JSON object...
so I changed the datatype to jsonstring from json...
still doesn't work.
Here is what returns my JSON data. UPDATED TO WHAT I AM NOW TRYING: I wanted to try putting the column names in the data... For some reason I thought that might help
public static object JsonHelper(TemplateModel model){
var values = model.Template;
var JsonDataList = new {
total = 1,
page = 1,
records = model.Template.Count,
rows = (from val in values
select new {
cell = //new string(
"[\"id\" :\"" + val.EncounterId +",\""+
//"\"MRN\" :" +
"\"MRN\" :\"" + val.MRN + ",\"" +
//"\"Hospital_Fin\" :" +
"\"Hospital_Fin\" :\"" + val.HostpitalFinNumber + ",\"" +
//"\"First_Name\" :"+
"\"First_Name\" :\"" + val.FirstName + ",\"" +
//"\"Last_Name\" :" +
"\"Last_Name\" :\"" + val.LastName + ",\"" +
//"\"Date_of_birth\" :" +
"\"Date_of_birth\" :\"" + val.DateOfBirth.ToString() + ",\"" +
//"\"Completed_Pathway\" :" +
"\"Completed_Pathway\" :\"" + val.CompletedPathway + ",\"" +
//"\"Completed_Pathway_Reason\" :" +
"\"Completed_Pathway_Reason\" :\"" + val.CompletedPathwayReason + ",\"" +
//"\"PCP_Appointment\" :" +
"\"PCP_Appointment\" :\"" + val.PCPAppointmentDateTime.ToString() + ",\"" +
//"\"Specialist_Appointment\" :" +
"\"Specialist_Appointment\" :\"" + val.SpecialistAppointmentDateTime.ToString() + ",\"" +
//"\"Admit_Date\" :" +
"\"Admit_Date\" :\"" + val.AdminDate.ToString() + "\"]"
})//.ToArray()
};
return JsonDataList;
}
plus...
return Json(DataRepository.JsonHelper(model.FirstOrDefault()), JsonRequestBehavior.AllowGet);
This is how I set up my jqGrid...
$(document).ready(function () {
$("#list").jqGrid({
shrinkToFit: false,
autowidth: true,
datatype: 'local',
mtype: 'POST',
colNames: ['Edit',
'MRN',
'Hospital Fin',
'First Name',
'Last Name',
'Date of birth',
'Completed Pathway',
'Completed Pathway Reason',
'PCP Appointment',
'Specialist Appointment',
'Admit Date'
],
colModel: [
{ name: 'Edit', width: 95, align: 'left' },
{ name: 'MRN', width: 125, align: 'left' },
{ name: 'Hospital_Fin', width: 145, align: 'left' },
{ name: 'First_Name', width: 115, align: 'left' },
{ name: 'Last_Name', width: 115, align: 'left' },
{ name: 'Date_of_birth', width: 145, align: 'left' },
{ name: 'Completed_Pathway', width: 125, align: 'left' },
{ name: 'Completed_Pathway_Reason', width: 165, align: 'left' },
{ name: 'PCP_Appointment', width: 115, align: 'left' },
{ name: 'Specialist_Appointment', width: 125, align: 'left' },
{ name: 'Admit_Date', width: 185, align: 'left' }],
rowNum: 10,
rowList: [5, 10, 20, 50],
sortname: 'Id',
sortorder: "desc",
viewrecords: true,
imgpath: '/Content/themes/UPMC-theme/images',
caption: 'My first grid'
}); })
I read somewhere online that setting the datatype to 'local' and then doing the setGridParam and trigger('reload') will help somehow or the other. Seems logical. But I am still a little unsure of how that would work... Still not working yet, but I am giving it the old college try...
UDPATE: Further explanation
My JsonHelper just tries to write out a valid JsonString... Does anybody have an example of how they do this regularly? Whenever I just use the standard Json ActionHelper thing... I guess I could make a different object return value, but that means I will have to mess around with more linq... And that is an adventure for another day.
**UPDATE2: Months have goneby"
Hello there. I have been distracted by another project for about a month. Now that it is starting to wind down, This code is starting to vex me once again. I feel like I am so close, but yet so far...
Anyway, Here is an example of the empty jqGrid that I was talking about...
As you can see, I have two rows of data, but neither one of them, has any of the data that they normally should...
Here is what the data looks like in debug mode...
["id" :"2005,""MRN" :"840108105,""Hospital_Fin" :"999999999999985,""First_Name" :"BETTY,""Last_Name" :"WHITE,""Date_of_birth" :"1/18/1951 12:00:00 AM,""Completed_Pathway" :",""Completed_Pathway_Reason" :",""PCP_Appointment" :"6/12/2012 12:00:00 AM,""Specialist_Appointment" :"6/12/2012 12:00:00 AM,""Admit_Date" :"7/5/2012 12:00:00 AM"]
["id" :"2025,""MRN" :"840108105,""Hospital_Fin" :"789654123000123,""First_Name" :"BETTY,""Last_Name" :"WHITE,""Date_of_birth" :"1/18/1951 12:00:00 AM,""Completed_Pathway" :",""Completed_Pathway_Reason" :",""PCP_Appointment" :"1/1/0001 12:00:00 AM,""Specialist_Appointment" :"1/1/0001 12:00:00 AM,""Admit_Date" :"7/6/2012 12:00:00 AM"]
That comes right out of my JSON helper... Which basically creates two string objects out of the Models that I get back...
This is what the JSON Data looks like on the client side right during the bind...
{"total":1,"page":1,"records":2,"rows":[{"cell":"[\"id\" :\"2005,\"\"MRN\" :\"840108105,\"\"Hospital_Fin\" :\"999999999999985,\"\"First_Name\" :\"BETTY,\"\"Last_Name\" :\"WHITE,\"\"Date_of_birth\" :\"1/18/1951 12:00:00 AM,\"\"Completed_Pathway\" :\",\"\"Completed_Pathway_Reason\" :\",\"\"PCP_Appointment\" :\"6/12/2012 12:00:00 AM,\"\"Specialist_Appointment\" :\"6/12/2012 12:00:00 AM,\"\"Admit_Date\" :\"7/5/2012 12:00:00 AM\"]"},{"cell":"[\"id\" :\"2025,\"\"MRN\" :\"840108105,\"\"Hospital_Fin\" :\"789654123000123,\"\"First_Name\" :\"BETTY,\"\"Last_Name\" :\"WHITE,\"\"Date_of_birth\" :\"1/18/1951 12:00:00 AM,\"\"Completed_Pathway\" :\",\"\"Completed_Pathway_Reason\" :\",\"\"PCP_Appointment\" :\"1/1/0001 12:00:00 AM,\"\"Specialist_Appointment\" :\"1/1/0001 12:00:00 AM,\"\"Admit_Date\" :\"7/6/2012 12:00:00 AM\"]"}]}
Just looking at my data, it seems kind of messed up. I am going to try and see if fixing it will make it look better. But if you have any other advice, I would definitely appreciate it.

I suppose that you have serious problems in the server code which you use. If you make $.ajax request with parameter dataType: "json" then $.ajax convert the data to the object. The response from the server seems as though you convert the returned object to JSON twice.
I suppose that you converted the object with total, page, records and rows properties first manually to JSON using JavaScriptSerializer or DataContractJsonSerializer and then returned the results string with return Json(myJsonString);. As the result the JSON string will be additionally encoded.
Moreover if you want use the data as datastr: result you have to use datatype: 'jsonstring' instead of datatype: 'json' which requires url parameter.
To tell the trust your code have other problems. $("#list").jqGrid({...}); create the grid from <table id="list"></table> element and the code can be executed only once. You current code is written so that the function bindData can be called multiple times on every form submit.
Additionally you use gridview: false which reduce the performance (you should always use gridview: true). The option imgpath not exist in jGrid since years. I suppose that you get some very very old example of jqGrid usage and tried to modify it to your purpose.
I would recommend you to get some more recent example, like from the answer or this one as the starting point. You should better use datatype: 'json' directly and send additional parameters to the server for example like it's described here or use $.serializeArray for example (see here).
UPDATED: There are NO JSON object. Either you have just an Object or you have a string which could represent an Object encoded corresponds to JSON standard.
You don't need to use any JsonHelper. The MVC action should just return Json(theObject) like
return new {
total = 1,
page = 1,
records = model.Template.Count,
rows = ...
};
Moreover the default format of JSON data for jqGrid described here. The code which you posted in JsonHelper contains
rows = (from val in values
select new {
invdata = new string[]{ ...}
}).ToArray()
and generate rows as array of objects without id property and with invdata property instead of cell. To read the data you need at least include jsonReader: {cell: "invdata"}. The better would be to return correct data having id. If some from the column tables could be interpreted as unique id of the row you can include key: true in the corresponding column, use jsonReader: {cell: ""} and fill rows as List<List<string>> or as array which elements as array or strings.

I think you are missing eval.
success: function (result) {
debugger;
var data = eval("(" + result.d + ")");
bindData(data);
}

Related

JSON.stringify add a carriage return

I am using postman for batch API calls and want a new line between each records (for the ease of others copy and pasting into csv/excel)
let responses = pm.collectionVariables.get('collectionResponses')
if(responses) {
responses = JSON.parse(responses);
} else {
responses = []
}
responses.push(pm.response.json());
pm.collectionVariables.set('collectionResponses', JSON.stringify(responses));
I tried
JSON.stringify(responses, '},', '},\n')
and that did not work
This is what the output looks like
{"success":true,"data":"0.5950391865600001\t0.49508964727322147\t193.383783","id":"2ec0a50f-862e-11ec-a41f-06c185e97372"},
{"success":true,"data":"0.5950391865600001\t0.49508964727322147","id":"410113f9-8630-11ec-a41f-06c185e97372"},
The simplest, most reliable way of doing this is to stringify each array element individually rather than all together:
const json = theArray.map(el => JSON.stringify(el)).join(",\n");
Live Example:
const theArray = [
{id: 1},
{id: 2,},
{id: 3},
];
const json = theArray.map(el => JSON.stringify(el)).join(",\n");
console.log(json);
I've left off the [] there because you seemed not to want them, but of course you could add them (`"[" + theArray.map(/.../) + "\n]").
Although JSON.stringify accepts a third parameter you can use for indentation (which triggers pretty-printing), it's awkard to use it for this purpose. You could provide a single space and then replace "\n " since a literal newline won't appear within a JSON value:
const json = JSON.stringify([1, 2, 3], null, 1)
.replace(/\n /g, "\n");
console.log(json);
...but it's a bit hacky.

EME Key ID different in session request vs. message (ClearKey)

What is the relationship between the kid supplied to MediaKeySession.generateRequest() and the one provided via MediaKeyMessageEvent?
If they are supposed to be the same - why are they different in the code below? note, this won't run here due to security restrictions
navigator.requestMediaKeySystemAccess("org.w3.clearkey", [{
initDataTypes: ['webm'],
audioCapabilities: [{
contentType: 'audio/webm; codecs="opus"'
}],
videoCapabilities: [{
contentType: 'video/webm; codecs="vp8"'
},
{
contentType: 'video/webm; codecs="vp9"'
}
],
}]).then((keySystemAccess) => {
return keySystemAccess.createMediaKeys();
}).then((mediaKeys) => {
var session = mediaKeys.createSession("temporary");
var keyId = "VHM2iIMGiSg";
var initData = '{"kids":["' + keyId + '"]}';
console.log(keyId);
session.addEventListener('message', (evt) => {
var requestJson = new TextDecoder().decode(evt.message);
var request = JSON.parse(requestJson);
console.log(request.kids[0]);
});
this.session.generateRequest("webm", new TextEncoder().encode(initData));
});
output:
VHM2iIMGiSg
eyJraWRzIjpbIlZITTJpSU1HaVNnIl19
expected output is for second line to also be VHM2iIMGiSg
eyJraWRzIjpbIlZITTJpSU1HaVNnIl19 is the base64url encoded value of initData that was passed to generateRequest.
The reason that request.kids[0] is the full value of initData and not the value of keyId is because generateRequest was invoked with the initDataType parameter set to webm. Had the initDataType parameter been set to keyids then request.kids[0] would be the value of keyId.
When the initDataType parameter is set to webm the initData parameter is expected to be a single key ID of one or more bytes. Whereas when the initDataType parameter is set to keyids the initData parameter is expected to be a JSON object encoded as UTF-8, containing a single member kids which is an array of base64url encoded Key ID(s).

Working with dates in W2UI and MySQL

I am using MySQL which stores dates in the format 'yyyy-mm-dd'.
I have a layout where one section shows a grid. The records in this grid display the date the record was first created. I need the date to be in the format of 'mm/dd/yyyy'.
This is how the date field in the grid is setup:
{ field: 'incident_date', caption: 'Incident Date', size: '150px', searchable: true, type: 'date', format: 'mm/dd/yyyy' },
I also have a form that opens for the user to edit the record. This is the date field code on that form:
{ name: 'incident_date', type: 'date', format: 'mm/dd/yyyy', required: true },
In w2ui-1.4.2.min.js I have these settings:
"date_format" : "mm/dd/yyyy",
"date_display" : "mm/dd/yyyy",
On the form the date field has a popup calendar that appears when this field is selected. When you select a date in the calendar the field gets filled in with the date you selected, in the format of "mm/dd/yyyy".
Now that you have an idea of how things are setup, when you save the record, any date you enter shows up in the grid as '0000-00-00'. if you use phpMyAdmin to look at the actual data in the table the date stored is '0000-00-00'
What I want is for the date to be displayed in the grid and in the form in the format of 'mm/dd/yyyy'. How can I accomplish this?
Thanks,
TD
For anyone who may have the same problem, the easiest way to fix this problem is to return your date from the server in mm-dd-yyyy format. For instance, if using MySQL you can use the following function in your SQL SELECT statment, date_format(yourDate, '%m-%d-%Y').
The other fix is to modify w2ui.js. In my opinion the date formatting in w2ui ver. 1.5 does not work correctly. The problem is with w2utils.formatters for dates. It uses the same date format for checking to see if it is a valid date as it does to format the date. So if yyyy-mm-dd is passed into params, it uses that to see if it is a valid date and fails. I have made some changes that worked for me and are listed below.
// MODIFIED LOCALE TO USE yyyy-mm-dd DATE FORMAT
var w2utils = (function ($) {
var tmp = {}; // for some temp variables
var obj = {
version : '1.5.RC1',
settings : {
"locale" : "en-us",
//"dateFormat" : "m/d/yyyy",
"dateFormat" : "yyyy-mm-dd",
"timeFormat" : "hh:mi pm",
"datetimeFormat" : "m/d/yyyy|hh:mi pm",
//"datetimeFormat" : "yyyy-mm-dd|hh:mi pm",
// MODIFIED DATE FORMATTER. ALWAYS RETRIEVE DEFAULT DATEFORMAT AND USE WHEN CHECKING FOR VALID DATE.
w2utils.formatters = {
'date': function (value, params) {
if (params === '') params = w2utils.settings.dateFormat; // DELETED
var defaultFormat = w2utils.settings.dateFormat; //ADDED
if (value == null || value === 0 || value === '') return '';
//var dt = w2utils.isDateTime(value, params, true);
//if (dt === false) dt = w2utils.isDate(value, params, true);
var dt = w2utils.isDateTime(value, defaultFormat, true); // CHANGED
if (dt === false) dt = w2utils.isDate(value, defaultFormat, true); // CHANGED
return '<span title="'+ dt +'">' + w2utils.formatDate(dt, params) + '</span>';
},
Hope this helps someone. I am working on getting these changes added to repository.
Thanks
John

Insert geometry values in mysql using node.js

I am using https://github.com/felixge/node-mysql module with node.js.
Mysql table has a field of type POINT. The module requires to send array of arrays to insert bulk records. But It doesn't seem to have option to specify data type.
So naturally, the following gets enclosed in quotes
var loc = "GeomFromText('POINT(" + lat + "," + lon + ")')";
Has anybody tried this? How can I convince the query builder to treat this as an sql function?
Or do I have to make my own query builder?
There is a pull request from kevinhikaruevans that does it. You can do something like that to convert objects to points:
if (typeof val === 'object') {
if(val.hasOwnProperty('lat') && val.hasOwnProperty('long')) {
return 'POINT(' + [val.lat, val.long].map(parseFloat).join(',') + ')';
}
}
Supposing you have a table mytable with only the field point of type POINT, you would insert them like this:
var points = [
[{ lat: 1, long: 4}],
[{ lat: 23, long: -8.345}]
];
var query = connection.query('INSERT INTO mytable(point) VALUES ?', [points], your_callback_func);
console.log("Query: " + query.sql);
This will generate a query similar to:
INSERT INTO mytable(point)
VALUES (POINT(1,4)), (POINT(23,-8.345))
This would convert any object with both lat and long fields to a MySQL point. If this is not an intended behavior, you could create a Point class and use it instead of plain objects, and in lib/protocol/SqlString.js check if the value is an instance of Point.
Try constructing a query to handle POINT() and batch where site is an object with properties and values shown below. This approach works for me.
pool.query('INSERT INTO table SET geometryField = POINT(?,?), ?',[coords.lat,coords.lng,site], function(err, response) {
{ sitename: 'A Site',
customer: 'A Customer',
country: 'AL',
timezone: 'America/Los_Angeles',
address1: '123 My Street',
city: 'MyCity',
state: 'WA',
postalcode: '98110'}

How to format datatime for json

I''m using EF to query the database using anonymous type.
here the code I use for EF
public JsonResult OverdueEventsCustom()
{
var eventCustomOverdue = _eventCustomRepository.FindOverdueEventsCustom();
return Json(eventCustomOverdue, JsonRequestBehavior.AllowGet);
}
public IQueryable<dynamic> FindOverdueEventsCustom()
{
DateTime dateTimeNow = DateTime.UtcNow;
DateTime dateTomorrow = dateTimeNow.Date.AddDays(1);
return db.EventCustoms.Where(x => x.DateTimeStart < dateTomorrow)
.Select(y => new { y.EventId, y.EventTitle, y.DateTimeStart});
}
Inspecting using the debugger I see the properties is in this format
Date = {16/08/2012 00:00:00}
The resultfor the JSON is
[{
"EventId": 1,
"EventTitle": "Homework Math",
"DateTimeStart": "\/Date(1345108269310)\/"
}, {
"EventId": 4,
"EventTitle": "Homework help with Annie",
"DateTimeStart": "\/Date(1345108269310)\/"
}, {
"EventId": 6,
"EventTitle": "Physic laboratory",
"DateTimeStart": "\/Date(1345108269310)\/"
}]
I need the the json in this format
"DateTimeStart": "(16/08/2012)"
Any idea what i'm doing wrong here? thanks for your help
Related articles
http://www.hanselman.com/blog/OnTheNightmareThatIsJSONDatesPlusJSONNETAndASPNETWebAPI.aspx
How do I format a Microsoft JSON date?
"\/Date(1345108269310)\/" is the correct way to pass a Date to javascript. The way I see it, you have two options here:
If you do not explicitly need the value as a date, you could just pass a string to the JSON variable, containing the pretty-printed date.
Something along the lines of:
DateTimeStart: String.Format("{0: dd-MM-yyyy}", myDate)
If you will still need to use the variable a a date in javascript (for calculations for example), the most consice and readably way would be to create a javascript function that converts said date into the pretty-printed string you want (I don't know if such a function already exists. It isn't too hard to create though:
function prettyDate(date) {
return date.getDate() + "-" + date.getMonth() + "-" + date.getFullYear();
}
I would suggest passing it along as a string from you code behind, as it is more readable. But that only works if you do not need to use the date except for displaying.