I'm trying to make my List to fill my jquery Datatable but I'm unable to do so, at the moment im writing my list to a file to access it by datatable in my view-model is my approach the correct one?
This is my code:
List<string> list = new List<string>();
foreach (var item in db.Pos)
{
var total = 0;
decimal costo = 0;
for (int i = 1; i <= 31; i++)
{
var value = 0;
if (item.Fecha.Day == i) { value = item.Cantidad; costo = costo + item.Total; }
total += value;
}
list.Add(item.Descripcion);
list.Add(item.Pdv);
list.Add(item.Rid);
list.Add(((costo / (total + 1)).ToString("C")));
for (int i = 1; i <= 31; i++)
{
var value = 0;
list.Add(value.ToString());
int month = item.Fecha.Month;
if (item.Fecha.Day == i) { value = item.Cantidad; list.Add(value.ToString()); }
}
list.Add(total.ToString());
list.Add((((costo / (total + 1)) * total).ToString("C")));
}
var json = JsonConvert.SerializeObject(new List<object>() { list });
System.IO.File.WriteAllText(#"\path.txt", json);
And my Datatable Ajax Call:
$(document).ready(function () {
var table = $('#pftable_hdr').DataTable({
ajax: {
url: "/path.txt",
dataSrc: ""
},
scrollY: "500px",
scrollX: true,
scrollCollapse: true,
fixedColumns: {
leftColumns: 3
}
});
});
Part of my Txt File Output:
[["ENS FRUTAS","REST","CENAS","$26.50","0","1","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","1","$26.50","CAFE AMER ILIMIT","REST","CENAS","$11.50","0","1","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","1","$11.50","QUESADILLAS TRAD (2)","REST","CENAS","$25.50","0","1","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","1","$25.50"]]
How can I fill my Jquery datatable with my list? My text file should have [] before and after the $data but I can't make that happen only at the first of the file and in the end.
Your backend code should look something like this. By doing this it will build a JSON string that is looking like this: [["","",""...],["","",""...],["","",""...]]
List<List<string>> list = new List<List<string>>();
foreach (var item in db.Pos)
{
List<string> listItem = new List<string>();
var total = 0;
decimal costo = 0;
for (int i = 1; i <= 31; i++)
{
var value = 0;
if (item.Fecha.Day == i) { value = item.Cantidad; costo = costo + item.Total; }
total += value;
}
listItem.Add(item.Descripcion);
listItem.Add(item.Pdv);
listItem.Add(item.Rid);
listItem.Add(((costo / (total + 1)).ToString("C")));
for (int i = 1; i <= 31; i++)
{
var value = 0;
listItem.Add(value.ToString());
int month = item.Fecha.Month;
if (item.Fecha.Day == i) { value = item.Cantidad; listItem.Add(value.ToString()); }
}
listItem.Add(total.ToString());
listItem.Add((((costo / (total + 1)) * total).ToString("C")));
list.Add(listItem);
}
var json = JsonConvert.SerializeObject(list);
System.IO.File.WriteAllText(#"\path.txt", json);
Try like this
list.Add("[");
list.Add(item.Descripcion);
// rest code....
list.Add((((costo / (total + 1)) * total).ToString("C")));
list.Add("]");
Will this work for your case ? Let know your comment
var json = JsonConvert.SerializeObject(new List<object>() { list });
In the above line list is already an object, then why you are creating a new object and assigning "list" to that object.
Try like below,
var json = JsonConvert.SerializeObject(list);
This will provide you the required result
Related
I want yo use test variable in update.js but it shows error when I use as variable but when I pass this value directly it works
can someone please tell me how can use dynamic variable to change quantity of existing products in cart
I have updated my code It will allow user to add only 5 items more than 5 items will be removed It will create string which will look like this
32082238341235:0,39470423048307:0,32164693278835:0,32164693835891:1
and finally the all IDs and qunatity will be updated by update.js
I have got error in last step its shows
{"status":404,"message":"Cart Error","description":"Cannot find variant"}
when i try to update all products
jQuery.getJSON('/cart.js', function(cart) {
var items_new = cart.items;
var count = 0;
count = cart.item_count;
var item_to_remove = count - 5;
if (count > 5) {
var item_to_remove = count - 5;
var combine = ""
if (item_to_remove > 0) {
for (var i = 0; i < items_new.length; i++) {
if (count > 5) {
var c_id = items_new[i].variant_id;
var c_quantity = items_new[i].quantity;
if (c_quantity >= item_to_remove) {
var q = c_quantity - item_to_remove
var data_multiple = c_id + ":" + q + ",";
debugger;
count = count - item_to_remove;
console.log(data_multiple);
var combine = combine + data_multiple;
} else {
var data_single = c_id + ":" + 0 + ",";
count = count - c_quantity;
item_to_remove = item_to_remove - c_quantity
console.log(data_single)
var combine = combine + data_single;
}
}
}
console.log(combine.slice(0, -1));
var test = combine.slice(0, -1);
console.log({
updates: {
test
}
});
jQuery.post('/cart/update.js', {
updates: {
test
}
});
}
t._rerenderCart()
}
t.sidebarDrawer.open()
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You need to store test as an object within parentheses {} and then pass to updates by using the spread ... operator.
var test = {39470423048307 : 0, 32164693278835 : 0, 32164693835891 : 1};
console.log({updates: {...test}});
jQuery.post('/cart/update.js', {updates:{...test}});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
In your updated code, you are passing a string to updates rather than an object. You should create an object from the data inside the for loop and pass that object to updates. See lines with // CHANGE HERE:
...
var combine = {};
if (item_to_remove > 0) {
for (var i = 0; i < items_new.length; i++) {
if (count > 5) {
var c_id = items_new[i].variant_id;
var c_quantity = items_new[i].quantity;
if (c_quantity >= item_to_remove) {
var q = c_quantity - item_to_remove;
// CHANGE HERE
combine[c_id] = q;
count = count - item_to_remove;
} else {
// CHANGE HERE
combine[c_id] = 0;
count = count - c_quantity;
item_to_remove = item_to_remove - c_quantity;
}
console.log(combine);
}
}
// CHANGE HERE
var test = combine;
console.log({
updates: test
});
jQuery.post('/cart/update.js', {
updates: test
});
...
I have been working for the last months with dygraphs. It is a incredible library and I have got great results but I´m having some problems to find the way of interpolating data from different signals to be shown in the same chart.
The data I received from different sensors have not the same timestamp for the different samples, so for the most of the points of the x axe timestamps I have only the value of one signal. The chart is plotted perfectly, but I would like to see the interpolated value of the rest of the signals in that x point I am pointing over. Below I have the chart I get.
Reading on the dygraph documentation I have seen that when you have independent series, it is possible to see at least the value "undefined" for the signals without data in that point of the x axe.
The csv I use to plot the data is shown below. It has the same structure indicated in the dygraph documentation but I don´t get this undefined label neither.
TIME,LH_Fuel_Qty,L_Left_Sensor_NP
1488801288048,,1.4411650490795007
1488801288064,0.478965502446834,
1488801288133,,0.6372882768113235
1488801288139,1.131315227899919,
1488801288190,1.847605177130475,
1488801288207,,0.49655791428536067
1488801288258,0.45488168748987334,
1488801288288,,1.3756073145270766
1488801288322,0.5636921255908185,
1488801288358,,1.1193344122758362
Thanks in advance.
This is an approach that does not add any data to your csv data and still provides interpolated values for all the columns as you move your mouse around. It adds a listener to the mousemove event within dygraph and interpolates the closest points for all of the data. At the moment I have simply shown it in an extra DIV that is after the graph but you can display it however you like:
function findNextValueIndex(data, column, start) {
var rows = data.length;
for (var i = start; i < rows; i++) {
if (data[i][column] != null) return (i);
}
return (-1);
}
function findPrevValueIndex(data, column, start) {
for (var i = start; i >= 0; i--) {
if (data[i][column] != null) return (i);
}
return (-1);
}
function interpolate(t0, t1, tmid, v0, v1) {
return (v0 + (tmid - t0) / (t1 - t0) * (v1 - v0));
}
function showValues(headers, colors, vals) {
var el = document.getElementById("info");
var str = "";
for (j = 1; j < headers.length; j++) {
str += '<p style="color:' + colors[j] + '";>' + headers[j] + ": " + vals[j] + "</p>";
}
el.innerHTML = str;
document.getElementById("hiddenDiv").style.display = "none";
}
function movecustom(event, dygraph, point) {
var time = dygraph.lastx_;
var row = dygraph.lastRow_;
var vals = [];
var headers = [];
var colors = [];
var cols = dygraph.rawData_[0].length;
// draw a line on the chart showing the selected location
var canvas = dygraph.canvas_;
var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.lineWidth = 1;
ctx.strokeStyle = "rgba(0,200,200,0.1)";
ctx.moveTo( dygraph.selPoints_[0].canvasx, 0);
ctx.lineTo( dygraph.selPoints_[0].canvasx, 1000);
ctx.stroke();
for (var j = 1; j < cols; j++) {
colors[j] = dygraph.colors_[j - 1];
if (dygraph.rawData_[row][j] == null) {
var prev = findPrevValueIndex(dygraph.rawData_, j, row - 1);
var next = findNextValueIndex(dygraph.rawData_, j, row + 1);
if (prev < 0)
vals[j] = dygraph.rawData_[next][j];
else if (next < 0)
vals[j] = dygraph.rawData_[prev][j];
else {
vals[j] = interpolate(dygraph.rawData_[prev][0], dygraph.rawData_[next][0], time, dygraph.rawData_[prev][j], dygraph.rawData_[next][j]);
}
} else {
vals[j] = dygraph.rawData_[row][j];
}
}
headers = Object.keys(dygraph.setIndexByName_);
showValues(headers, colors, vals);
}
window.onload = function() {
new Dygraph(
document.getElementById('graph'), document.getElementById('csvdata').innerHTML, {
connectSeparatedPoints: true,
drawPoints: true,
labelsDiv: "hiddenDiv",
interactionModel: {
'mousemove': movecustom
}
}
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/dygraph/2.0.0/dygraph.js"></script>
<div id="graph" style="height:120px;"></div>
<div id="info"></div>
<div id="hiddenDiv" style="display:none"></div>
<pre id="csvdata" style="display:none">
TIME,LH_Fuel_Qty,L_Left_Sensor_NP
1488801288048,,1.4411650490795007
1488801288064,0.478965502446834,
1488801288133,,0.6372882768113235
1488801288139,1.131315227899919,
1488801288190,1.847605177130475,
1488801288207,,0.49655791428536067
1488801288258,0.45488168748987334,
1488801288288,,1.3756073145270766
1488801288322,0.5636921255908185,
1488801288358,,1.1193344122758362
</pre>
It seems that the best way to do this is to massage the data before submitting it to the dygraph call. This means the following steps:
1) parse the csv file into an array of arrays.
2) go through each line of the array to find where the holes are
3) interpolate to fill those holes
4) modify the constructed arrays to be displayed by dygraph
5) call dygraph
Not the most attractive code, but seems to work...
function findNextValueIndex(data, column, start) {
var rows = data.length;
for(var i=start;i<rows;i++) {
if(data[i][column].length>0) return(i);
}
return(-1);
}
function interpolate(t0, t1, tmid, v0, v1) {
return((v0 + (tmid-t0)/(t1-t0) * (v1-v0)).toString());
}
function parseCSV(string) {
var data = [];
// first get the number of lines:
var lines = string.split('\n');
// now split the first line to retrieve the headings
var headings = lines[0].split(",");
var cols = headings.length;
// now get the data
var rows=0;
for(var i=1;i<lines.length;i++) {
if(lines[i].length>0) {
data[rows] = lines[i].split(",");
rows++;
}
}
// now, fill in the blanks - start by finding the first value for each column of data
var vals = [];
var times = [];
for(var j=1;j<cols;j++) {
var index = findNextValueIndex(data,j,0);
vals[j] = parseFloat(data[index][j]);
}
// now put those start values at the beginning of the array
// there is no way to calculate the previous value of the sensor missing from the first sample
// so we use the first reading and duplicate it
for(var j=1;j<cols;j++) {
data[0][j] = vals[j].toString();
times[j] = parseInt(data[0][0]);
}
// now step through the rows and interpolate the missing values
for(var i=1;i<rows;i++) {
for(var j=1;j<cols;j++) {
if(data[i][j].length>0) {
vals[j] = parseFloat(data[i][j]);
times[j] = parseInt(data[i][0]);
}
else {
var index = findNextValueIndex(data,j,i);
if(index<0) // no more data in this column
data[i][j] = vals[j].toString();
else
data[i][j] = interpolate(times[j],parseInt(data[index][0]),parseInt(data[i][0]),vals[j],data[index][j]);
}
}
}
// now convert from strings to integers and floats so dygraph can handle it
// I've also changed the time value so that it is relative to the first element
// it will be shown in milliseconds
var time0 = parseInt(data[0][0]);
for(var i=0;i<rows;i++) {
data[i][0] = parseInt(data[i][0]) - time0;
for(var j=1;j<cols;j++) {
data[i][j] = parseFloat(data[i][j]);
}
}
var obj = {
labels: headings,
data: data
}
return(obj);
}
window.onload = function () {
var data_obj = parseCSV(document.getElementById('csvdata').innerHTML);
new Dygraph(
document.getElementById('graph'), data_obj.data,
{
labels: data_obj.labels,
connectSeparatedPoints: true,
drawPoints: true
}
);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dygraph/2.0.0/dygraph.js"></script>
<div id="graph" style="height:200px;"></div>
<pre id="csvdata" style="display:none">
TIME,LH_Fuel_Qty,L_Left_Sensor_NP
1488801288048,,1.4411650490795007
1488801288064,0.478965502446834,
1488801288133,,0.6372882768113235
1488801288139,1.131315227899919,
1488801288190,1.847605177130475,
1488801288207,,0.49655791428536067
1488801288258,0.45488168748987334,
1488801288288,,1.3756073145270766
1488801288322,0.5636921255908185,
1488801288358,,1.1193344122758362
</pre>
Does
connectSeparatedPoints: true
Not do what you need?
My web API accepts below JSON format (this is input parameter)
[{
"atrSpaUserId": "47fe8af8-0435-401e-9ac2-1586c8d169fe",
"atrSpaClassLegendId": "00D18EECC47E7DF44200011302",
"atrSpaCityDistrictId": "144d0d78-c8eb-48a7-9afb-fceddd55622c"},
{
"atrSpaUserId": "47fe8af8-0435-401e-9ac2-1586c8d169fe",
"atrSpaClassLegendId": "00D18EECC47E7DF44200011302",
"atrSpaCityDistrictId": "144d0d78-c8eb-48a7-9afb-fceddd55622c"
}
]
I am building request below in javascript.
var administratorId = '47fe8af8-0435-401e-9ac2-1586c8d169fe'
var districtId = '144d0d78-c8eb-48a7-9afb-fceddd55622c'
var atrUserLegendsInputs
for (i = 0; i < list.get_items().get_count() ; i++)
{
atrUserLegendsInputs += { atrSpaUserId: administratorId, atrSpaClassLegendId: list.getItem(i).get_value(), atrSpaCityDistrictId: districtId } + ',';
}
atrUserLegendsInputs = atrUserLegendsInputs.substring(0, atrUserLegendsInputs.length - 1);
var legendIds = '[' + atrUserLegendsInputs + ']';
var atrDistrictLegend = { districtID: cityDistrictId, legendIDs: legendIds };
var test = JSON.stringify(atrDistrictLegend);
getting error message:
{["The input was not valid."]}
I am not sure whether I am doing the right way. I am new to Json and ajax calls. Can you one please help me to fix this issue
Try this code
var administratorId = '47fe8af8-0435-401e-9ac2-1586c8d169fe';
var districtId = '144d0d78-c8eb-48a7-9afb-fceddd55622c';
//* create empty array for legends
var atrUserLegendsInputs = [];
for (i = 0; i < list.get_items().get_count() ; i++) {
//* put some values into legends' array
atrUserLegendsInputs.push({
atrSpaUserId: administratorId,
atrSpaClassLegendId: list.getItem(i).get_value(),
atrSpaCityDistrictId: districtId
});
}
var atrDistrictLegend = {
districtID: cityDistrictId,
legendIDs: atrUserLegendsInputs
};
var test = JSON.stringify(atrDistrictLegend);
How to ensure i have a dynamic increment of Alphabets in a new cell on left side, next to each cell in a row which is dynamically created based on the option chosen in Select. This newly generated alphabet will be considered as bullet points/serial number for that particular row's text box.
jsfiddle
js code
$(document).ready(function(){
var select = $("#Number_of_position"), table = $("#Positions_names");
for (var i = 1; i <= 100; i++){
select.append('<option value="'+i+'">'+i+'</option>');
}
select.change(function () {
var rows = '';
for (var i = 0; i < $(this).val(); i++) {
rows += "<tr><td><input type='text'></td></tr>";
}
table.html(rows);
});
});
html
<select id="Number_of_position">
</select> <table id="Positions_names">
</table>
This is essentially a base26 question, you can search for an implementation of this in javascript pretty easily - How to create a function that converts a Number to a Bijective Hexavigesimal?
alpha = "abcdefghijklmnopqrstuvwxyz";
function hex(a) {
// First figure out how many digits there are.
a += 1; // This line is funky
var c = 0;
var x = 1;
while (a >= x) {
c++;
a -= x;
x *= 26;
}
// Now you can do normal base conversion.
var s = "";
for (var i = 0; i < c; i++) {
s = alpha.charAt(a % 26) + s;
a = Math.floor(a/26);
}
return s;
}
So you can do
$(document).ready(function(){
var select = $("#Number_of_position"), table = $("#Positions_names");
for (var i = 1; i <= 100; i++){
select.append('<option value="'+i+'">'+i+'</option>');
}
select.change(function () {
var rows = '';
for (var i = 0; i < $(this).val(); i++) {
rows += "<tr><td>" + hex(i) + "</td><td><input type='text'></td></tr>";
}
table.html(rows);
});
});
Heres the example http://jsfiddle.net/v2ksyy7L/6/
And if you want it to be uppercase just do
hex(i).toUpperCase();
Also - this will work up to any number of rows that javascript can handle
if i have understood you correctly, that's maybe what you want:
http://jsfiddle.net/v2ksyy7L/3/
I have added an array for the alphabet:
var alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
and then added the output to your "render" loop:
rows += "<tr><td>" + alphabet[i] + " <input type='text'></td></tr>";
I am trying to draw a Google visualization pie chart based on below JSON. I am having issues since Google takes numerical data, instead of just plain objects.
For example, I want a pie chart based on UseCase. Pie chart will list VDI,Upgrade,DEMO and show its proportion related to total. Please help.
Here is the JSON example
[{"Id":0,"ProcessedTime":"2012/01","Approver":"zoo","POC":"POC1","UseCase":"VDI"},{"Id":0,"ProcessedTime":"2012/02","Approver":"zoo","POC":"POC1","UseCase":"Upgrade"},{"Id":0,"ProcessedTime":"2012/03","Approver":"zoo","POC":"POC2","UseCase":"DEMO"},{"Id":0,"ProcessedTime":"2012/04","Approver":"victor","POC":"POC2","UseCase":"DEMO"},{"Id":0,"ProcessedTime":"2012/05","Approver":"victor","POC":"POC3","UseCase":"VDI"},{"Id":0,"ProcessedTime":"2012/06","Approver":"victor","POC":"POC3","UseCase":"Upgrade"},{"Id":0,"ProcessedTime":"2012/05","Approver":"tom","POC":"POC3","UseCase":"VDI"},{"Id":0,"ProcessedTime":"2012/06","Approver":"tom","POC":"POC3","UseCase":"Upgrade"}]
// Full source
google.setOnLoadCallback(drawChart);
function drawChart() {
$.get('/Home/GetData', {},
function (data) {
var tdata = new google.visualization.DataTable();
tdata.addColumn('string', 'UseCase');
tdata.addColumn('int', 'Count');
// Reservation based on UseCase
var ReservationByUseCase = [];
for (var i = 0; i < data.length; i++) {
var d = data[i];
// If not part of array.. Add it
if ($.inArray(d.UseCase, ReservationByUseCase) === -1)
{
var UseCaseValue = d.UseCase;
var UseCaseCountValue = 1;
ReservationByUseCase.push({ UseCase: UseCaseValue, UseCaseCount: UseCaseCountValue });
}
// If part of the array.. Increase count
if ($.inArray(d.UseCase, ReservationByUseCase) !== -1) {
var cUseCase = ReservationByUseCase[$.inArray(d.UseCase, ReservationByUseCase)];
cUseCase.UseCaseCount = cUseCase.UseCaseCount + 1;
ReservationByUseCase[$.inArray(d.UseCase, ReservationByUseCase)] = cUseCase
}
}
for (var i = 0; i < ReservationByUseCase.length; i++) {
tdata.addColumn(ReservationByUseCase[i].UseCaseValue, ReservationByUseCase[i].UseCaseCountValue)
alert(ReservationByUseCase[i].UseCaseValue);
alert(ReservationByUseCase[i].UseCaseCountValue);
}
var options = {
title: "Reservations"
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(tdata, options);
});
}
You just need to loop through the data and add up each UseCase:
var ndata = {}
var data = [{"Id":0,"ProcessedTime":"2012/01","Approver":"zoo","POC":"POC1","UseCase":"VDI"},{"Id":0,"ProcessedTime":"2012/02","Approver":"zoo","POC":"POC1","UseCase":"Upgrade"},{"Id":0,"ProcessedTime":"2012/03","Approver":"zoo","POC":"POC2","UseCase":"DEMO"},{"Id":0,"ProcessedTime":"2012/04","Approver":"victor","POC":"POC2","UseCase":"DEMO"},{"Id":0,"ProcessedTime":"2012/05","Approver":"victor","POC":"POC3","UseCase":"VDI"},{"Id":0,"ProcessedTime":"2012/06","Approver":"victor","POC":"POC3","UseCase":"Upgrade"},{"Id":0,"ProcessedTime":"2012/05","Approver":"tom","POC":"POC3","UseCase":"VDI"},{"Id":0,"ProcessedTime":"2012/06","Approver":"tom","POC":"POC3","UseCase":"Upgrade"}];
for (i = 0; i < data.length; i++) {
var d = data[i];
if (ndata[d["UseCase"]] == null) {
ndata[d["UseCase"]] = 1
} else {
ndata[d["UseCase"]] = ndata[d["UseCase"]] + 1
}
}
console.log(ndata);
Here's a fiddle: http://jsfiddle.net/znj0kLsg/
This is what I've came up with... Will this work?
// Reservation based on UseCase
var ReservationByUseCase = [];
for (var i = 0; i < data.length; i++) {
var d = data[i];
// If not part of array.. Add it
if ($.inArray(d.UseCase, ReservationByUseCase) === -1)
{
var UseCaseValue = d.UseCase;
var UseCaseCountValue = 1;
ReservationByUseCase.push({ UseCase: UseCaseValue, UseCaseCount: UseCaseCountValue });
}
// If part of the array.. Increase count
if ($.inArray(d.UseCase, ReservationByUseCase) !== -1) {
var cUseCase = ReservationByUseCase[$.inArray(d.UseCase, ReservationByUseCase)];
cUseCase.UseCaseCount = cUseCase.UseCaseCount + 1;
ReservationByUseCase[$.inArray(d.UseCase, ReservationByUseCase)] = cUseCase
}
}