Issue with json datasource and datatables - datatables

I am trying to use a json retrieved from an external API and saved as a variable.
I keep getting the error:
DataTables warning: table id=pageTable - Requested unknown parameter '0' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4
I am initializing the table after the table is built and I have 4 columns both in the head and in the body.
The paging works but the table itself comes out empty.
What am I missing?
function build_table(feed_items){
console.log(feed_items)
var list = "";
for(i=0; i< feed_items.length; i++){
list += '<tr class="text-center">';
list += '<td>'+feed_items[i]["ns2:feedDate"]+'</td>';
list += '<td>'+feed_items[i]["ns2:feedStatus"]+'</td>';
list += '<td>'+feed_items[i]["ns2:feedType"]+'</td>';
list += '<td>'+feed_items[i]["ns2:itemsReceived"]+'</td>';
list += '</tr>';
}
$("tbody").html(list);
$('#pageTable').DataTable({
"pageLength": 10,
data: feed_items,
columns: [
{title: "ns2:feedDate"},
{title: "ns2:feedStatus"},
{title: "ns2:feedType"},
{title: "ns2:itemsReceived"}
],
stateSave: true,
dom: 'lBfrtip',
buttons: [
'excelHtml5',
'csvHtml5',
'pdfHtml5'
]
})
}

Related

Karate API framework - Validate randomly displayed items in response

I am using Karate API framework for the API automation and came across with one scenario, the scenario is when I am hitting a post call it gives me some json response and few of the items are having tags whereas few of them are showing tags as blank to get all the tags below is the feature file scenario line
* def getTags = get response.items[*].resource.tags
It is giving me response as
[
[
],
[
],
[
{
"tags" : "Entertainment"
}
],
[
],
[
{
"tags" : "Family"
}
],
As you can see out of 5 or 6 tags only 2 tags are having the value, so I want to capture if any tags value is showing or not. What would be the logic for the assertion considering these tags can all come as empty and sometimes with come with a string value. In above case "Family" & "Entertainment"
Thanks in advance !
* match each response.items[*].resource.tags == "##string"
This will validate that tags either doesn't exist or is a string.
I think you can use a second variable to strip out the empties, or maybe your original JsonPath should use .., you can experiment:
* def allowed = ['Music', 'Entertainment', 'Documentaries', 'Family']
* def response =
"""
[
[
],
[
],
[
{
"tags":"Entertainment"
}
],
[
],
[
{
"tags":"Family"
}
]
]
"""
* def temp = get response..tags
* print temp
* match each temp == "#? allowed.contains(_)"

In ramda.js, does fromPairs change the order of elements?

I receive large array of pairs:[number, {number,number, big array of numbers}]
First I add my main pair to beginning of the array:
prepend([target[0], {count : target[1].length, overall : target[1].length, items:target[1]}]),
Next I do:
Promise.all([
to_file_json(
token.user_id,
'connections_data',
JSON.stringify(
fromPairs(r[0])
))...
And I can find my main pair somewhere in the middle of my file.
So my question is, could fromPairs possibly change the order? If yes what can I do to prevent this?
Edit:
additional info:
1)r variable correspond to [[number, Friends][], Float64Array[]]
2) target variable correspond to [number,number[]]
3) Beginning of element which i'm prepend, it's always the biggest one, and it got in the middle of the file somehow.
"136444868":{"count":304,"overall":304,"items":[19363,234566,290677,1375661,2030175,2131497,2593602,2596894,2816890,2869895,3170377,3437884,3486703,3504543,4046799,4235623,5366101.....
4) Friends type :
interface Friends {
count:number,
overall:number,
items:number[]
};
sample data
{
"19363":{"count":5,"overall":3088,"items":[51177198,53119509,136035431,209482119,216378147]}
,"234566":{"count":6,"overall":6803,"items":[290677,3504543,23180680,75311610,178479726,196401211]}
,"290677":{"count":19,"overall":2213,"items":[234566,5686439,7873089,11175816,13726459,20697213,23180680,27419631,55209039,74493674,75311610,125041200,133272552,139307068,159591583,168386810,173599247,178429642,189097165]}
,"1375661":{"count":0,"overall":76,"items":[]},"2030175":{"count":14,"overall":86,"items":[2596894,6507568,11681736,17736119,49557638,117771194,127144880,141523415,147264238,153044182,156925389,160656334,223530741,262311445]},"2131497":{"count":16,"overall":301,"items":[13598979,15682478,20357560,20869716,27419631,30869837,33650605,40129023,68976427,88146695,90648231,101105191,118193129,145163503,216503667,387266562]},
I expect the issue is that you do a prepend without removing the element from its later place in the list.
Then you might end up with some data like:
[
[ 2131497, { count: 16, overall: 301, items: [ /* .. * ] } ], // duplicate
[ 19363, { count: 5, overall: 3088, items: [ /* .. * ] } ],
[ 234566, { count: 6, overall: 6803, items: [ /* .. * ] } ],
[ 290677, { count: 19, overall: 2213, items: [ /* .. * ] } ],
[ 1375661, { count: 0, overall: 76, items: [ /* .. * ] } ],
[ 2030175, { count: 14, overall: 86, items: [ /* .. * ] } ],
[ 2131497, { count: 16, overall: 301, items: [ /* .. * ] } ] // duplicate
]
Then, when you do fromPairs, the later version will override the earlier one, and it will end up back in the list at the original position, as per this line from the documentation:
If a key appears in multiple pairs, the rightmost pair is included in the object.
But... even if you fix this, you will still not get the behavior you want, because of the object property iteration order specification, which says that integer keys of an object are iterated first, in numeric order, before the non-integer keys. Axel Rauschmayer has a very readable description of this.
These complexities are one of the reasons that Ramda (disclaimer: I'm one of the authors) has not created a foldObj implementation.

Trying to create a yadcf filter for a column with images

I need to create a filter on a tipical columns created with images: each field is an image with this format:
<img src='http://lab.onclud.com/psm/blackcircle.png' class='notasg'>
I've created a fiddle example here: fiddle
An explication:
there are only 2 diferents status: [assigned/not assigned] although there are 4 diferents images (black, red, yellow and green).
Only black image correspond to not assigned status. The others three ones (red, yellow and green) correspond to assigned status.
As you could see, I've tried to differentiate those status by class HTML tag in img elements (notasg/asgn).
Thanks in advance.
PD:
I'm getting data from a json, so I can't put:
<td data-search="notassigned">
directly on HTML code. As a solution, I've used createdCell (columnDefs option) as you could see on the next updated to create data-search attribute on td element fiddle.
In this one, as you could test, your previously created filter doesn't work. I've tried some solutions, but no one has worked.
Please help me again on this one. Thanks in advance.
You can make use of the datatables HTML5 data-* attributes, and then tell yadcf to rely on this dt feature with the use of html5_data
So your td will look something like
<td data-search="assigned"><img src='http://lab.onclud.com/psm/redcircle.png' class='asgn'></td>
and yadcf init will look like
var oTable = $('#example').DataTable();
yadcf.init(oTable, [
{
column_number: 0,
html5_data: 'data-search',
filter_match_mode: 'exact',
data: [{
value: 'assigned',
label: 'Assigned'
}, {
value: 'notassigned',
label: 'Not assigned'
}]
}]);
Notice that I used filter_match_mode: 'exact', because I used data-search="notassigned" and data-search="assigned", and since the assigned word included inside notassigned I had to tell yadcf to perform an exact search, this can be avoided if you will use unique search term in your data-search= attribute,
See working jsfiddle
Another solution as introduced by kthorngren from datatables forum is to use the following dt init code
var oTable = $('#example').DataTable({
columnDefs: [{
targets: 0,
render: function(data, type, full, meta) {
if (type === 'filter') {
return full[0].search('asgn') >=1 ? "assigned" : full[0].search('notasg') >= 1 ? "notassigned" : data
} else {
return data
}
}
}],
});
and yadcf init (removed html5_data)
yadcf.init(oTable, [
{
column_number: 0,
filter_match_mode: 'exact',
data: [{
value: 'assigned',
label: 'Assigned'
}, {
value: 'notassigned',
label: 'Not assigned'
}]
}
]);
third option - look here

How to generate jQuery DataTables rowId client side?

The jQuery DataTables reference shows an example of setting the rowId option to a column from the data source (server side). This setting is used for the "select" extension and retaining row selection on Ajax reload.
Is there any way to generate the row identifier value 1) client side, or 2) as a combination of multiple columns from the data source?
Example data source:
{
"data": [
{
"aid": 5421,
"bid": 4502,
"name": "John Smith"
}
}
Code:
$("#datatable").DataTable({
select: true,
//rowId: "aid" each row ID is the value of the "aid" column
// e.g., <tr id="5421">
//rowId: 0 each row ID is the value of the 0-indexed column
// e.g., <tr id="5421"> (same as above)
rowId: [0, 1] // How? row ID combined value of 2+ columns
// e.g. <tr id="5421-4502">
rowId: "random" // How? random generated client-side ID
// e.g., <tr id="id34e04">
});
Apparently there's no way to do this directly. As a workaround, you could use the ajax.dataSrc option and/or the rowId option:
// Example using dataSrc option to manipulate data:
$("#example").dataTable({
ajax: {
url: "data.json",
dataSrc: function (json) {
for (var i = 0, ien = json.data.length; i < ien; i++) {
json.data[i][0] = 'View Message';
}
}
}
});
This worked for me:
$("#datatable").DataTable({
...
'createdRow': function(nRow, aData, iDataIndex) {
$(nRow).attr('id', 'row' + iDataIndex); // or if you prefer 'row' + aData.aid + aData.bid
},
...
});
I updated it from a question that seems to be a duplicate of this one. The createdRow callback is documented here.

View pictures or images inside Jquery DataTable

May I know if it is possible to put pictures or images into the rows of DataTables (http://datatables.net/) and how does one goes in doing it?
yes, simple way (Jquery Datatable)
<script>
$(document).ready(function () {
$('#example').dataTable({
"processing": true, // control the processing indicator.
"serverSide": true, // recommended to use serverSide when data is more than 10000 rows for performance reasons
"info": true, // control table information display field
"stateSave": true, //restore table state on page reload,
"lengthMenu": [[10, 20, 50, -1], [10, 20, 50, "All"]], // use the first inner array as the page length values and the second inner array as the displayed options
"ajax":{
"url": "#string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~"))/Home/AjaxGetJsonData",
"type": "GET"
},
"columns": [
{ "data": "Name", "orderable" : true },
{ "data": "Age", "orderable": false },
{ "data": "DoB", "orderable": true },
{
"render": function (data, type, JsonResultRow, meta) {
return '<img src="Content/Images/'+JsonResultRow.ImageSrcDB+'">';
}
}
],
"order": [[0, "asc"]]
});
});
</script>
[edit: note that the following code and explanation uses a previous DataTables API (1.9 and below?); it translates easily into the current API (in most cases, just ditch the Hungarian notation ("fnRowCallback" just becomes "rowCallback" for example) but I have not done so yet. The backwards compatibility is still in place I believe, but you should look for the newer conventions where possible]
Original reply follows:
What Daniel says is true, but doesn't necessarily say how it's done. And there are many ways. Here are the main ones:
1) The data source (server or otherwise) provides a complete image tag as part of the data set. Don't forget to escape any characters that need escaping for valid JSON
2) The data source provides one or more fields with the information required. For example, a field called "image link" just has the Images/PictureName.png part. Then in fnRowCallback you use this data to create an image tag.
"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
var imgLink = aData['imageLink']; // if your JSON is 3D
// var imgLink = aData[4]; // where 4 is the zero-origin column for 2D
var imgTag = '<img src="' + imgLink + '"/>';
$('td:eq(4)', nRow).html(imgTag); // where 4 is the zero-origin visible column in the HTML
return nRow;
}
3) Similar to above, but instead of adding a whole tag, you just update a class that has the image as a background. You would do this for images that are repeated elements rather than one-off or unique pieces of data.
You mean an image inside a column of the table?
Yes, just place an html image tag
like this
<img src="Images/PictureName.png">
instead of putting data (some string) into a column just put the above html tag....
Asp.net core DataTables
The following code retrieve the image from a folder in WWWroot and the path in the DB field ImagePath
{
"data": "ImagePath",
"render": function (data) {
return '<img src="' + data + '" class="avatar" width="50" height="50"/>';
}
}
In case the Name of the picturefile is put together out of one or more informations in the table, like in my case:
src="/images/' + Nummer + Belegnummer + '.jpg"
you can make it that way:
var table = $('#Table').DataTable({
columnDefs: [
{
targets: 0,
render: getImg
}
]
});
function getImg(data, row, full) {
var Nummer = full[1];
var Belegnummer = full[4];
return '<img src="/images/' + Nummer + Belegnummer + '.jpg"/>';}
The picture is in the first column, so Targets = 0 and gets the Information from the same row.
It is necessary to add the parameters data and row.
It is not necessary to outsource it into a seperate function, here getImg, but it makes it easier to debug.