Enabling sorting for a column using DataTable - javascript

I am having a html table getting populated using JSON by an ajax call as follows -
$.ajax({
type: "POST",
url: "my_url",
data: JSON.stringify(result),
async: true,
dataType: "json",
contentType: "application/json; charset= Shift-JIS",
success: function (response) {
glResp = response;
populateTable(glResp);
},
error: function (error) {
console.log(error);
//alert("Error!!");
}
});
The function used for populating the table is as follows -
function populateTable(finalObject) {
var obj = finalObject;
var headers1 = ['Name', 'ID', 'Job', 'Salary','JoiningDate'];
var table = $("<table id='my-table' />");
var columns = headers1;
columns.unshift('');
var columnCount = columns.length;
var row = $(table[0].insertRow(-1));
for (var i = 0; i < columnCount; i++) {
if (i == 0) {
var headerCell = $("<th><input type='button' id='sort'></th>");
row.append(headerCell);
}
else {
var headerCell = $("<th/>");
headerCell.html([columns[i]]);
row.append(headerCell);
}
}
$.each(obj, function (i, obj) {
$row = '<tr><td><input type="checkbox"></td><td>' + obj.Name + '</td><td>' + obj.ID+ '</td><td>' + obj.Job + '</td><td>' + obj.Salary + '</td><td>'+ obj.JoiningDate+'</td></tr>';
table.append(row);
});
var dvTable = $("#dvCSV");
dvTable.html("");
dvTable.append(table);
}
Now I want to enable sorting for only two columns - ID & JoiningDate using DataTable plugin. I tried to understand the api but everytime something or the other problem came up. (E.g. for ID = M981-01) (E.g. for date: 2016-10-24) Can anyone help me to implement DataTable plugin or any other suitable approach to enable sort with respect to ID and JoiningDate?

Related

Loop a column value in a table using ajax call

I hope you are fine!
I'm new in coding so I'm facing of something without results.
I have this type of code here in JS.
key: 'generateChart2',
value: function generateChart2() {
var self = this;
var Jahr1 = [];
var years1 = "";
for (var i = 0; i < $('#mf123_select_jahr').val().length; i++) {
if (i > 0) years1 += ","
years1 += $('#mf123_select_jahr').val()[i];
}
var postedData1 = {};
postedData1.years1 = years1;
console.log(postedData1);
$.ajax({
url: "data/json.dashboard.php?call=chart2",
data: postedData1,
dataType: 'json',
type: 'POST',
success: function (dataGraph2) {
var trHTML='';
$.each(dataGraph2, function (key, value) {
for (var i in postedData1) {
Jahr1.push(postedData1[i].years1);
}
console.log(postedData1.years1);
trHTML +=
'<tr><td >' + value.Mandant +
'</td><td >' + thousandSepNeu(value.Jahr1, 2) + " €" +
'</td><td >' + value.Growth +
'</td></tr>';
});
$('#dataGraph2').append(trHTML);
}
});
}
The value.Mandant and the value.Growth are doing well. The problem that I have is that the for loop does not work. I need to thr postedData1 to choose whenever the user choose the year to show him the results.
The output of console.log(postedData1); is:
Am I making a mistake? I know that the problem is on the for loop.
Please any advice i would appreciate it.
:)

GET Method always receives null value

I´m trying to get a list with Ajax when a modal shows up, but for some reason my method always receives a null variable. I´m sure that the issue is on the Ajax call, because if I test my method using 1 as an argument instead of the value from Ajax, it returns the list the way I wanted.
JS:
$("#visualizacao").on('show.bs.modal', function (e) {
var data = $(e.relatedTarget);
var idAviso = data.context.dataset.avisoid;
$.ajax({
type: 'GET',
url: 'ListaVisuAviso/' +idAviso,
success: function (response) {
$('#visu-table tbody').empty();
var trHTML = '';
$.each(response, function (i, item) {
trHTML += '<tr><td>' + item.NOME + '</td><td>' + item.DATA_HORA + '</td><td>' + item.DEPARTAMENTO + '</td></tr>';
});
$('#visu-table tbody').append(trHTML);
$('#modal-visu').modal('show');
},
error: function (xhr) {
console.log(xhr);
}
});
$('#modalAviso').modal('show');
});
C#
[HttpGet]
public JsonResult ListaVisuAviso(string avisoId)
{
//var avisoid = 1;
var avisoid = Convert.ToDecimal(avisoId);
var query =
from a in _dataContext.TB_AVISOS_NOTIFICACOES
join b in _dataContext.VW_USUARIOS4 on a.USUARIO_PR equals b.USUARIOID
where a.AVISO_ID == avisoid
select new VisuAviso()
{
NOME = b.NOME,
DATA_HORA = a.DATA_HORA.ToString(),
DEPARTAMENTO = b.DEPARTAMENTO
};
return Json(query, JsonRequestBehavior.AllowGet);
}
I discovered what was causing the "issue". To use this way of sending the parameter, my route config on the backend was expecting it to be a parameter called "id". So I would either change my receiving parameter to "id" instead of "avisoId" like the following:
[HttpGet]
public JsonResult ListaVisuAviso(string id)
{
//var avisoid = 4;
var avisoid = Convert.ToDecimal(id);
var query =
from a in _dataContext.TB_AVISOS_NOTIFICACOES
join b in _dataContext.VW_USUARIOS4 on a.USUARIO_PR equals b.USUARIOID
where a.AVISO_ID == avisoid
select new VisuAviso()
{
NOME = b.NOME,
DATA_HORA = a.DATA_HORA.ToString(),
DEPARTAMENTO = b.DEPARTAMENTO
};
return Json(query, JsonRequestBehavior.AllowGet);
Or, I would have do specify the name of the parameter on the JS, like this "?usuarioId=", this way the route would know that it´s not the id parameter:
$("#visualizacao").on('show.bs.modal', function (e) {
var idAviso = $(e.relatedTarget).attr('data-avisoid');
$.ajax({
type: 'GET',
url: 'ListaVisuAviso/?usuarioId =' + idAviso,
dataType: 'json',
success: function (response) {
$('#visu-table tbody').empty();
var trHTML = '';
$.each(response, function (i, item) {
trHTML += '<tr><td>' + item.NOME + '</td><td>' + item.DATA_HORA + '</td><td>' + item.DEPARTAMENTO + '</td></tr>';
});
$('#visu-table tbody').append(trHTML);
$('#modal-visu').modal('show');
},
error: function (xhr) {
console.log(xhr);
}
});
$('#modalAviso').modal('show');
});

Categorising SharePoint list items on a HTML using Javascript and JSON

I have a JavaScript page which is querying a SharePoint list. The information on the list regards IT hardware, Lap Tops, Tablets etc. The user inputs the specific type, and I have a drop down of more general hardware types.
This is what I've got:
and this is what I need:
So under the hardware headings the specifics get categorised. What's the best way to do this? JavaScript below:
function getDeviceDetails() {
var txtTitle = "";
var txtOverview = "";
var txtAccessories = "";
var txtDevicetype = "";
var txtTypicalDeviceUsage ="";
var txtKnownSystemIssues ="";
var txtLifeCycles = "";
var txtTrafficlight = "";
var imgDevicePicture = "";
var tempLCS2 = "";
var query = "http://collaboration-dev.norgine.com/sites/it/SystemInventory/_vti_bin/listdata.svc/Devices?$expand=Priority&$filter=Id eq " + window.DeviceId + "";
var call = $.ajax({
url: query,
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});
call.done(function (data,textStatus, jqXHR){
$.each(data.d.results, function(index, item) {
var tempID = item.Id;
var tempTitle = item.Title;
var DeviceOverView = item.Description;
var AccessDetails = item.Accessories;
var DeviceKind = item.DevicetypeValue;
var Usage = item.TypicalUsage;
var DevicePriority = item.PriorityValue;
var DeviceImage = item.DeviceImage;
txtTitle = "<p>"; //+ LifeCycleStart + "</p><p>" + LifeCycleStatus + "</p>";
txtOverview = "<p>" + DeviceOverView + "</p>";
txtAccessories = "<p>" + AccessDetails + "</p>";
txtDevicetype = "<p>" + DeviceKind + "</p>";
txtTypicalDeviceUsage = "<p>" + Usage + "</p>";
txtTrafficlight = "<p>" + DevicePriority + "</p>";
imgDevicePicture = "<img src='" + DeviceImage + "'>";
});
$('#devicedetails').append($(txtTitle));
$('#deviceoverview').append($(txtOverview));
$('#devicekind').append(txtDevicetype);
$('#deviceacc').append(txtAccessories);
$('#deviceuse').append(txtTypicalDeviceUsage);
$('#devicestatus').append(txtTrafficlight);
$('#imageContainer').append("<img src='/sites/IT/SiteAssets/"+txtTrafficlight.replace(/<[^>]*>/g, '')+".png' />");
$('.deviceimage').append(imgDevicePicture);
});
call.fail(function (jqXHR,textStatus,errorThrown){
alert("Error retrieving data: " + jqXHR.responseText);
});
}
You're taking records from a SharePoint list and displaying them grouped by a common column value. There are two ways to accomplish this.
Option 1: Perform Separate Queries
If you have three categories of devices (e.g. Laptop, Desktop, and Tablet) you can query the SharePoint list once for each category of items you wish to retrieve.
var urlEndpoint = "http://collaboration-dev.norgine.com/sites/it/SystemInventory/_vti_bin/listdata.svc/Devices$expand=Priority,Devicetype&$filter=Id eq " + window.DeviceId + " and ";
var laptopFilter = "DevicetypeValue eq 'Laptop'",
desktopFilter = "DevicetypeValue eq 'Desktop'",
tabletFilter = "DevicetypeValue eq 'Tablet'";
$.ajax({
url: urlEndpoint + laptopFilter,
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
}).done(displayLaptopResults);
$.ajax({
url: urlEndpoint + desktopFilter,
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
}).done(displayDesktopResults);
$.ajax({
url: urlEndpoint + tabletFilter,
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
}).done(displayTabletResults);
function displayLaptopResults(data){ /* your code here */ }
function displayDesktopResults(data){ /* your code here */ }
function displayTabletResults(data){ /* your code here */ }
This is only possible if you know the different categories beforehand and can compose your queries to filter against those categories. It has the advantage of working with smaller chunks of data at a time, and might be necessary when dealing with large lists.
If you don't know all the possible categories then consider the next option.
Option 2: Perform One Query and Post-process The Results
Alternatively, you can get all the results and place them into an in-memory data structure according to their category before displaying the records on the page.
Instead of having an array of items...
var results = [item1, item2, item3, item4, item5]
You'll have a hashmap with an array property for each category.
var results = {
category1: [item1, item4],
category2: [item2, item3],
category3: [item5]
}
The following code example demonstrates how you can process an array of items to categorize them, then render the results afterwards.
var data = {d:{results:[
{title:"X1 Carbon",DevicetypeValue:"laptop"},
{title:"T470",DevicetypeValue:"laptop"},
{title:"MS Surface Pro3",DevicetypeValue:"tablet"},
{title:"X270",DevicetypeValue:"laptop"},
{title:"M910",DevicetypeValue:"desktop"},
{title:"MS Surface Pro4",DevicetypeValue:"tablet"}]}};
var i = 0, len = data.d.results.length, item, category, devicesByCategory = {};
// loop through the results and add them to the devicesByCategory object
while(i < len){
item = data.d.results[i];
category = item.DevicetypeValue;
if(devicesByCategory[category]){
// if devicesByCategory already has an array for this item's category, add the item to it
devicesByCategory[category].push(item);
}else{
// otherwise, create a new array for the category
devicesByCategory[category] = [item];
}
i++;
}
// loop through all the categories and render them
for(var category in devicesByCategory){
var div = createCategorySection(category);
addResultsToSection(div,devicesByCategory[category]);
}
function createCategorySection(value){
var div = document.getElementById("output").appendChild(document.createElement("div"));
div.appendChild(document.createElement("h1")).appendChild(document.createTextNode(value));
return div;
}
function addResultsToSection(section,results){
var ul = section.appendChild(document.createElement("ul"));
i = 0; len = results.length;
while(i < len){
item = results[i];
ul.appendChild(document.createElement("li")).appendChild(document.createTextNode(item.title));
i++;
}
}
<div id="output"></div>

Fix the headers in html table populated by ajax

I am populating a html table using ajax call in the following manner-
$.ajax({
type: "POST",
url: "my_url",
data: JSON.stringify(result),
async: true,
dataType: "json",
contentType: "application/json; charset= Shift-JIS",
success: function (response) {
glResp = response;
populateTable(glResp);
},
error: function (error) {
console.log(error);
//alert("Error!!");
}
});
Function that I am using to populate the table is as follows -
JS -
function populateTable(finalObject) {
var obj = finalObject;
var headers1 = ['Name', 'City', 'Job', 'Salary'];
var table = $("<table id='my-table' />");
var columns = headers1;
columns.unshift('');
var columnCount = columns.length;
var row = $(table[0].insertRow(-1));
for (var i = 0; i < columnCount; i++) {
if (i == 0) {
var headerCell = $("<th><input type='button' id='sort'></th>");
row.append(headerCell);
}
else {
var headerCell = $("<th/>");
headerCell.html([columns[i]]);
row.append(headerCell);
}
}
$.each(obj, function (i, obj) {
$row = '<tr><td><input type="checkbox"></td><td>' + obj.Name + '</td><td>' + obj.City + '</td><td>' + obj.Job + '</td><td>' + obj.Salary + '</td></tr>';
table.append(row);
});
var dvTable = $("#dvCSV");
dvTable.html("");
dvTable.append(table);
}
Now I want the table headers to be fixed on top when the data is being scrolled. Any idea as to how this can be implemented?
You can use a plugin to have a fixed position to your header columns,
http://mkoryak.github.io/floatThead/
Hope this link will help you.
For fix the header you can add thead for title element (th) and tbody for the chlid tr element, with display:block for both and overflow:auto for tbody element.
var tab = '[{"Name":"check","City":"check","job":"check","Salary":"check"},{"Name":"check","City":"check","job":"check","Salary":"check"},{"Name":"check","City":"check","job":"check","Salary":"check"},{"Name":"check","City":"check","job":"check","Salary":"check"},{"Name":"check","City":"check","job":"check","Salary":"check"},{"Name":"check","City":"check","job":"check","Salary":"check"}]'
tab = JSON.parse(tab);
populateTable(tab);
function populateTable(finalObject) {
var obj = finalObject;
var headers1 = ['Name', 'City', 'Job', 'Salary'];
var table = $("<table id='my-table' />");
var columns = headers1;
columns.unshift('');
var columnCount = columns.length;
var th = ""
for (var i = 0; i < columnCount; i++) {
if (i == 0) {
var headerCell = "<th><input type='button' id='sort'></th>";
th = th + headerCell;
}
else {
var headerCell = "<th>"+[columns[i]]+"</th>";
// headerCell.html();
th = th + headerCell;
}
}
table.prepend("<thead>"+th+"</thead>")
$.each(obj, function (i, obj) {
row = '<tr><td><input type="checkbox"></td><td>' + obj.Name + '</td><td>' + obj.City + '</td><td>' + obj.job + '</td><td>' + obj.Salary + '</td></tr>';
table.append(row);
});
var dvTable = $("#dvCSV");
dvTable.html("");
dvTable.append(table);
}
table{
width:100%;
}
td, th {
min-width: 100px;
}
tbody{
overflow: auto;
display: block;
height: 100px;
}
thead{
display:block;
text-align:left;
background:green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dvCSV"><div>

How to send table column values from a Javascript page to a C# page using Jquery

I have values that come from a dynamically created table from it's selected rows. inside each selected row i want all the td.innerText values that belong to be sent to a C# page, but i don't know how to. I was using JSON but I dont know if i used it properly.
function selectedRows()
{
var selectedItems = $('#ScannedLabelTable').find(':checkbox:checked').parents('tr');
var serial, kanbanNumber, customer, description, quantity;
$.each(selectedItems, function (i, item) {
var td = $(this).children('td');
for (var i = 0; i < td.length; ++i)
{
serial = td[1].innerText;
kanbanNumber = td[2].innerText;
customer = td[3].innerText;
description = td[4].innerText;
quantity = td[5].innerText;
}
console.log(serial + ' ' + kanbanNumber + ' ' + customer + ' ' + description + ' ' + quantity);
});
$.ajax({
url: SEND_TO_TEXTFILE_PAGE
, data: "labelSerial=" + serial + "&kanbanNumber=" + kanbanNumber + "&customer="
+ customer + "&description=" + description + "&quantity=" + quantity
, dataType: 'json'
, success: function (status) {
if (status.Error) {
alert(status.Error);
}
}
, error: Hesto.Ajax.ErrorHandler
});
}
EDIT: sorry I must have read this too quickly. This should do it. create an array and add the data object to it in the loop.
If you just create a json object using key value pairs you can send that object to your c# controller.
function selectedRows() {
var selectedItems = $('#ScannedLabelTable').find(':checkbox:checked').parents('tr');
var serial, kanbanNumber, customer, description, quantity;
var dataArray = new Array();
$.each(selectedItems, function (i, item) {
var td = $(this).children('td');
for (var i = 0; i < td.length; ++i)
{
var InfoObject = {
serial: td[1].innerText;
kanbanNumber: td[2].innerText;
customer: td[3].innerText;
description: td[4].innerText;
quantity: td[5].innerText;
};
dataArray.push(InfoObject);
}
});
$.ajax({
url: SEND_TO_TEXTFILE_PAGE
, data: dataArray
, dataType: 'json'
, success: function (status) {
if (status.Error) {
alert(status.Error);
}
}
, error: Hesto.Ajax.ErrorHandler
});
}

Categories