I am a beginner in using jQuery Float Chart. Now I try to bind the chat with server side values. I need to build an array structure like below.
data = [{
label: 'Test 1',
data: [
[1325376000000, 1200],
[1328054400000, 700],
[1330560000000, 1000],
[1333238400000, 600],
[1335830400000, 350]
]
},];
My Server Response
My question is how to push items in this array of array. I already try to build an array like this:
var data = new Array();
var chartOptions;
$.each(graphdata, function (key, value) {
data.push({
label: value.label,
data: $.each(value.data, function (key, value) {
Array(value.X, value.Y);
})
})
});
Edits
Graph shows in webpage
But it's not working.
The problems is that $.each return collection that iterates on - the collection you don't want to.
You can use underscore library that contains function map to project value into another:
var postData = [{label:"test1", "data": [ {X: "10", Y:"11"}, {X: "12", Y: "13"}] }];
var data = []
$.each(postData, function (key, value) {
data.push({
label: value.label,
data: _(value.data).map(function(innerVal) {
var arr = new Array();
arr.push(innerVal.X);
arr.push(innerVal.Y);
return arr;
})
})
});
Here is jsFiddle: click!
Related
I am new to using react.js, using a C# API, and trying to use the semantic-UI dropdown that allows HTML in the content of the dropdown items.
I'm having trouble returning the "content" field below. It looks like a jsx:element type, not a string or number like the other types.
I can hardcode it, but I can't return it from the API.
Here is the example from the Semantic documentation which seems like an invalid JSON to me. For now, I've given up on this, but still curious how JSON like this is supposed to be returned from c# .net core API.
const options = [
{
key: 1,
text: 'Mobile',
value: 1,
content: (
<Header icon='mobile' content='Mobile' subheader='The smallest size' />
),
},
{
key: 2,
text: 'Tablet',
value: 2,
content: (
<Header
icon='tablet'
content='Tablet'
subheader='The size in the middle'
/>
),
},
{
key: 3,
text: 'Desktop',
value: 3,
content: (
<Header icon='desktop' content='Desktop' subheader='The largest size' />
),
},
]
This is my the code in the API that currently sends the dropdown items:
[HttpGet(Name = "GetCaseDropdown")]
public IEnumerable<CaseDropdownItem> Get()
{
var db = new CaseDBContext();
var records = (from x in db.Cases
select new CaseDropdownItem()
{
content = "<b>"+ x.StrCnCasenum + "</b>" + " " + x.StrCnName, // Does not render within parentheses which is required
text = x.StrCnName,
value = x.StrCnCasenum,
key = x.StrCnCasenum
}).ToArray();
return records;
}
And the react code that fetches the data:
fetch("casedropdown")
.then((response) => response.json())
.then((data) =>
setCaseOptions(
data.map((x) => {
return { key: x.key, text: x.text, value: x.value, content: x.content };
})
)
);
I'm using EF6 + MVC for a site. The dataTables editor is used for an UI. One table has a field 'StartDate'. It is a datetime type in the SQL Server.
It works fine until when I try to edit the 'StartDate' value. From the browser debug, I can see that the JSON send from backend to UI is in the timestamp format, i.e. /Date(1541923200000)/ .
In the dataTables, I convert this to the correct local datetime format, so it shows correctly.
However, I could not figure out how to do this in Editor plugin. It always shows the /Date(1541923200000)/ .
The code I use is:
editorAdvertisement = new $.fn.dataTable.Editor({
ajax: '/APN/GetAdvertisementData',
table: "#tblAdvertisements",
fields: [{
label: "StartDate",
name: "AdvStartDate"
, type: "datetime"
, format: 'MM\/DD\/YYYY h:mm a'
}, {
label: "Deadline",
name: "AdvDeadline"
, type: "datetime"
}, {
label: "TitleOfAdv",
name: "TitleOfAdv"
}, {
label: "ListPrice",
name: "ListPrice"
}
]
});
var tbl = $('#tblAdvertisements').DataTable({
pageLength: 10,
dom: '<"html5buttons"B>lTfgitp',
ajax: '/APN/GetAdvertisementData'
,
columns: [
{
data: "AdvStartDate", name: "AdvStartDate"
, type: "datetime"
, render: function (value) {
var r = convertDate(value);
return r;
}
, "autoWidth": true
},
{
data: "AdvDeadline", name: "AdvDeadline"
, type: "datetime"
, render: function (value) {
var r = convertDate(value);
return r;
}
, "autoWidth": true
},
{ data: "TitleOfAdv", name: "TitleOfAdv", "autoWidth": true },
{
data: "ListPrice", name: "ListPrice", "autoWidth": true
, render: $.fn.dataTable.render.number(',', '.', 0, '$')
}
],
order: [1, 'asc'],
select: {
style: 'os',
selector: 'td:first-child'
},
buttons: [
{ extend: "create", editor: editorAdvertisement }
, { extend: "edit", editor: editorAdvertisement }
, { extend: "remove", editor: editorAdvertisement }
]
, select: true
, searching: false
, paging: false
});
In the controller
[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
public ActionResult GetAdvertisementData()
{
var request = HttpContext.Request.Form;
var settings = Properties.Settings.Default;
using (var db = new Database(settings.DbType, settings.DbConnection))
{
var response = new Editor(db, "Advertising", new[] { "AdvertisingID" })
.TryCatch(false)
.Model<Advertising2>()
.Field(new Field("AdvStartDate")
.Validator(Validation.DateFormat(
"MM/dd/yyyy",
new ValidationOpts { Message = "Please enter a date in the format MM/dd/yyyy" }
))
.GetFormatter(Format.DateTime("yyyy-MM-dd HH:mm:ss", "MM/dd/yyyy"))
.SetFormatter(Format.DateTime("MM/dd/yyyy", "yyyy-MM-dd HH:mm:ss"))
)
.Field(new Field("AdvDeadline")
.Validator(Validation.DateFormat(
"MM/dd/yyyy",
new ValidationOpts { Message = "Please enter a date in the format MM/dd/yyyy" }
))
.GetFormatter(Format.DateSqlToFormat("MM/dd/yyyy"))
.SetFormatter(Format.DateFormatToSql("MM/dd/yyyy"))
)
.Field(new Field("TitleOfAdv"))
.Field(new Field("ListPrice"))
.Process(request)
.Data();
return Json(response, JsonRequestBehavior.AllowGet);
}
}
I could not figure it out after a long search. Anyone had the same issue? Any solution?
Check Out moment.js (https://momentjs.com), download moment-with-locales.js and add it to your ScriptBundle in BundleConfig.cs.
Then in your datatable's javascript code you can render the column in proper date/time format as follows. Note: my locale is 'pt' (Portugal). The date column is rendered as dd/mm/yyyy hh:mm (once again, see the formatting options in https://momentjs.com).
"columns": [
{ "data": "OriginName" },
{ "data": "SmsID" },
{ "data": "DestinationNumber" },
{
"data": "SMSDeliveryDate",
"render": function (data) {
var re = /-?\d+/;
var m = re.exec(data);
var d = new Date(parseInt(m[0]));
moment.locale('pt');
var m = moment(d).format('L LTS');
return m;
}
},
{ "data": "SmsStateDesc" }
],
Hope this info can be useful. I too was stuck with this for a few hours...
José
I had the same problem and eventually found the answer on the Editor forum.
If you look with fiddler (a great tool for seeing what happens) you
see the JSON has this format you get. If you look in the code in
visual studio express and capture what you got before passing it to
JSON you see something like "{12/12/2012 12:12}". So actually the
cause is the JSON.
Refactoring to just the essentials in your first column it should read like this.
This approach solved my problem without any problem. This version is designed to render null dates as blanks, otherwise format as directed. (Update: refactored the answer again, seeing that the next morning the formatted codes were not behaving as expected.)
{
data: "AdvStartDate",
render: function (data, type, full) {
if (data != null) {
var dtStart = new Date(parseInt(data.substr(6)));
return dtStart.toLocaleDateString();
} else {
return "";
}
}
I have a datatable i wish to use defer render on, I am not sure what the issue is, my controller method returns an array of json objects. See code below.
**Datatable setup **
This is called when the page is loaded.
var $dtTable = $("#tblPlayer");
$dtTable.dataTable({
bFilter: false,
pageLength: 10,
paging: true,
autoWidth: true,
columns:
[
null,
{ "orderDataType": "dom-text", type: "string" },
{ "orderDataType": "dom-text", type: "string" },
{ "orderDataType": "dom-text-numeric" },
{ "orderDataType": "dom-text-numeric" },
{ "orderDataType": "dom-text-numeric" },
{ "orderDataType": "dom-text-numeric" },
{ "orderDataType": "dom-text-numeric" },
null,
null,
null
],
"ajax": "Player/GetSetPlayers",
"deferRender": true
});
Controller methods
public object[] GetSetPlayers()
{
var players = GetPlayers();
_players = new object[players.Count];
for (var i = 0; i < players.Count; i++)
{
_players[i] = players[i];
}
return _players;
}
GetSetPlayers() returns an array of json objects, the result below is an exampel of what index 0 and 1 will contain.
Response
[
{
"product":25000,
"rank":1,
"dirty_money":25000,
"id":"b4b41b18edbb49b9ae80be5e768b6b80",
"name":"Dan",
"ban_status":0,
"edit":"<a href='/support/player_gamedata/b4b41b18edbb49b9ae80be5e768b6b80/game' class='btn'><i class='icon-folder-close'></i></a>",
"credit":30,
"clean_money":20000,
"ban":"<a href='/support/ban_player/by_id/b4b41b18edbb49b9ae80be5e768b6b80/' class='btn'><i class='icon-remove'></i></a>",
"supplies":25000
},
{
"product":25000,
"rank":1,
"dirty_money":25000,
"id":"3cac6e366170458686021eaa77ac4d6d",
"name":"Dan",
"ban_status":0,
"edit":"<a href='/support/player_gamedata/3cac6e366170458686021eaa77ac4d6d/game' class='btn'><i class='icon-folder-close'></i></a>",
"credit":30,
"clean_money":20000,
"ban":"<a href='/support/ban_player/by_id/3cac6e366170458686021eaa77ac4d6d/' class='btn'><i class='icon-remove'></i></a>",
"supplies":25000
}
]
I think you need to specify a "data" attribute on each column that needs to be populated from the returned data. Otherwise it doesn't know what attribute on the json object goes to each column. If you defined your data as an array of arrays instead of an array of objects this wouldn't be required.
Additionally you aren't specifying a "dataSrc" option which isn't required but if it isn't set I believe it expects the returned JSON to be of the form:
{
data: [ {...}, {...} ]
}
So it would be helpful if you could add in the raw response to the ajax request.
EDIT1:
Ok so double checked and yes it does want an object array assigned to the "data" attribute on the JSON object so you can do something like this to fix this without having to modify anything on the server. Just change your ajax option to this:
"ajax": {
"url": "Player/GetSetPlayers",
"dataSrc": function ( json ) {
// We need override the built in dataSrc function with one that will
// just return the object array instead of looking for a "data"
// attribute on the "json" object. Note if you ever want to add
// serverside sorting/filtering/paging you will need to move your table
// data to an attribute within the JSON object.
return json;
}
}
So you will probably be good once you do both of the fixes above.
I have created one string array in jquery of name array[] and pushed values to it.
How can I send this array in query string?
For example window.location.href('ViewData?array');
And how can I get back the array data from query string in jquery itself ?
Please advice?
This is very easy to achieve with jQuery as it has a helper function called param().
var myData = {
name: "John Doe",
age: 23,
children: [{
name: "Jane Doe",
age: 13,
children: []
},
{
name: "John Doe Jr.",
age: 16,
children: []
}
],
}
var p = $.param(myData)
The results:
"name=John+Doe&age=23&children%5B0%5D%5Bname%5D=Jane+Doe&children%5B0%5D%5Bage%5D=13&children%5B1%5D%5Bname%5D=John+Doe+Jr.&children%5B1%5D%5Bage%5D=16"
You can use it like so:
window.location = "/MyController/MyAction?" + p;
As for getting parameters from query strings, please refer to the following question: How can I get query string values in JavaScript?
Another thing you can do is use an ajax call, this way you don't have to serialize the data yourself as it is done for you automatically.
$.ajax({
url: "/MyController/MyAction",
data: myData,
dataType: "json",
type: "POST",
success: function(data){
//'data' is your response data from the Action in form of a javascript object
}
})
I think this is what you are looking for. Let me know if I get it wrong. I copied $.parseParams from this link. You can also see working code here
(function($) {
var re = /([^&=]+)=?([^&]*)/g;
var decodeRE = /\+/g; // Regex for replacing addition symbol with a space
var decode = function (str) {return decodeURIComponent( str.replace(decodeRE, " ") );};
$.parseParams = function(query) {
var params = {}, e;
while ( e = re.exec(query) ) {
var k = decode( e[1] ), v = decode( e[2] );
if (k.substring(k.length - 2) === '[]') {
k = k.substring(0, k.length - 2);
(params[k] || (params[k] = [])).push(v);
}
else params[k] = v;
}
return params;
};
})(jQuery);
var s=["abc", "xyz", "123"];
var queryString=$.param({a:s});
console.log("object to query string: ", queryString);
console.log("query string to object: ", $.parseParams(queryString));
I have following json data
var data = [
Object {
Data = 3,
Label = "Statement -2"
},
Object {
Data = 3,
Label = "this is a very long stat...s a very long statement"
}
]
I want to convert it into the following:
var data: [{
data : [[0,50]],
label : "Comedy"
}, {
data: [[0, 10]],
label : "Action"
}, {
data: [[0, 60]],
label : "Romance"
}, {
data: [[0, 20]],
label : "Drama"
}]
Can any one help me?
Your Source JSON is not right.
Change your source JSON like this, and call method to transform.
var data = [
{
data : 3,
Label : "Statement -2"
},
{
data : 6,
Label : "this is a very long stat...s a very long statement"
}]
for(var item in data){
data[item].data = [0,data[item].data]
}
You could iterate over your array of objects and use toArray() to get your array of arrays.
for (var i=0;i<data.length;i++) {
data[i] = data[i].toArray();
}
Not tested thou ;-)