jQuery dataTable sort with ajax loaded data - javascript

I have several rows that include some lazy loaded data. For instance,
<table border="1">
<tr>
<th>Employee</th><th>Sales</th>
</tr>
<tr>
<td>Michale</td><td>1000</td>
</tr>
<tr>
<td>Kim</td><td id="kimSales"></td>
</tr>
<tr>
<td>John</td><td id="johnSales"></td>
</tr>
</table>
The problem is, I have to retrieve some data after page loaded because of some reasons. Let's suppose kimSales is 1500, and johnSales is 2500.
<script>
$(document).on('ready', function(e){
$('#kimSales').text(1500);
$('#johnSales').text(2500);
})
</script>
In this situation, I want to sort properly with lazy loaded data. You know, jQuery dataTable has sorting features through click header of columns, like https://datatables.net I couldn't sort these data properly. The sorted data is not ascending, or dsc --- maybe dataTable couldn't recognize after loaded data.
What I tried :
<script>
$(document).on('ready', function(e){
$('#kimSales').text(1500);
$('#johnSales').text(2500);
})
table.dataTable(); // not properly working
</script>

I hope you want to achieve sorting based on the second column. Try this in the table initialization code and with your preferred sorting technique [asc,desc]
$('table').DataTable( {
"order": [[ 1, "desc" ]]
} );

If you update cell's data BEFORE initializing the table, it should work correctly.
Also you should be initializing the table in ready event handler. For example:
$(document).on('ready', function(e){
$('#kimSales').text(1500);
$('#johnSales').text(2500);
var table = $('#example').DataTable();
});
If you update cell's data AFTER initializing the table, you need to use cell().invalidate() API method and redraw the table.
For example:
$(document).on('ready', function(e){
var table = $('#example').DataTable();
$('#kimSales').text(1500);
table.cell($('#kimSales').closest('td')).invalidate();
$('#johnSales').text(2500);
table.cell($('#johnSales').closest('td')).invalidate();
table.draw();
});

Related

In Ember.js why does 'afterRender' not trigger on a redraw?

I'm trying to call a function when new data gets added to a table in a view, but it's not working. I'm using Ember.js 2.5
I have two models, client and user. A client has many users.
My view to list clients looks like this:
<table class="table table-striped" id="admin-table">
<thead>
<tr>
<th>Primary User</th>
<th>User Email</th>
<th>Join Date</th>
</tr>
</thead>
<tbody>
{{#each model as |client|}}
<tr>
<td>{{client.primaryUser.name}}</td>
<td>{{client.primaryUser.email}}</td>
<td>{{client.createdAt}}</td>
</tr>
{{/each}}
</tbody>
</table>
primaryUser is a computed property containing the first user for each client.
primaryUser: Ember.computed('users', function(){
return this.get('users.firstObject');
})
Problem
I'm using the jquery tablesorter library which adds sorting and filtering to the table. Because the primaryUser get's loaded by AJAX I need to call $('#admin-table').trigger('update') when new data is added in order to have the library index the new information.
Here's what I'm doing:
modelObserver: function() {
Ember.run.next(this, this.updateTable);
}.observes('model.#each.primaryUser')
I've tried both run.next, and run.scheduleOnce('afterRender'..) and the result is always the same. The updateTable function triggers before all of the primaryUser objects are rendered.
Here's what happens if I put a debugger within this.updateTable:
it only triggers once, when a cached user (me) is rendered. The empty cells in this table populate a few ms later when the rest of the user information is ajaxed in, but updateTable never re-runs.
I can confirm at this point that the other primary user fields are not in the DOM:
Help
Is there a way to trigger an event once all objects have been rendered? I've using Ember.run.sync() as mentioned in this answer, but it didn't help.
Everything's fine but you need to manually check if all users are rendered. There's no other option. The code would look like this I think. It's a bit primitive, but I think you get the idea that you just can check the DOM.
modelObserver: function() {
var areRendered = [];
Ember.$('table#admin-table tr').each(function (index, element) {
$(element).find('td').each(function (anotherIndex, anotherElement) {
if (anotherIndex <= 1) { //This is because according to your screenshot you don't have to check all the cells, just first two if I'm not mistaking.
if (anotherElement.text()) {
areRendered.push(true);
} else {
areRendered.push(false);
}
}
});
});
if (!areRendered.contains(false)) { //Checking if there were any element without data.
Ember.run.next(this, this.updateTable);
}
}.observes('model.#each.primaryUser')
Hope it helps!

jQuery DataTables - Access all rows data

I'm using jQuery DataTables and want to copy all rows (save in JavaScript array) upon clicking the header checkbox.
I want to find where jQuery DataTables store the HTML for remaining page of rows, so I can navigate through JavaScript then check it there or set property checked to true.
Something like this one.
Other information:
I use data from an ajax source(serverside:false), all data is returned.
When I click page 1, all the rows remain Checked.
SOLUTION
There are many methods that could be used for that purpose. You can use rows().data() to get the data for the selected rows.
Example:
var table = $('#example').DataTable();
var data = table
.rows()
.data();
alert( 'The table has ' + data.length + ' records' );
DEMO
See this jsFiddle for code and demonstration.
I find the generated element by jQuery DataTables using this code, and I can copy the whole tr element that hides when paging the DataTables.
$('#example').DataTable().rows().iterator('row', function(context, index){
var node = $(this.row(index).node());
//node.context is element of tr generated by jQuery DataTables.
});
If you do this:
$('#table').DataTable().rows().data();
you get a lot of unnecessary data.
If you just want the table data you can do this:
$('#table').DataTable().rows().data().toArray();
Using
tableObject.rows().data()
will return all the data from the table.
Set the pageLength:
$('#example').dataTable( {
"pageLength": 50
} );

Why AJAX response is not in sortable manner

I am using sorttable.jsfor table sorting and my table is updated in every 3 sec by ajax response but the response is not in sorted manner as i expect it to be.
Index page
<div id="resDiv">
<table id="myTable1" class="sortable">
<thead>
<tr><th id="person">Person</th><th id="monpay">Monthly pay</th></tr>
</thead>
<tbody>
<tr><td>Jan Molby</td><td>£12,000</td></tr>
<tr><td>Steve Nicol</td><td>£8,500</td></tr>
<tr><td>Steve McMahon</td><td>£9,200</td></tr>
<tr><td>John Barnes</td><td>£15,300</td></tr>
</tbody>
<tfoot>
<tr><td>TOTAL</td><td>£45,000</td></tr>
</tfoot>
</table>
</div>
Append new table data
ajax response is :
<table id="myTable" class="sortable">
<thead>
<tr><th>Person</th><th>Monthly pay</th></tr>
</thead>
<tbody>
<tr><td>prabha Molby</td><td>£12,000</td></tr>
<tr><td>abcd Nicol</td><td>£8,500</td></tr>
<tr><td>steev McMahon</td><td>£9,200</td></tr>
<tr><td>John Barnes</td><td>£15,300</td></tr>
</tbody>
<tfoot>
<tr><td>TOTAL</td><td>£55,000</td></tr>
</tfoot>
</table>
JavaScript
$(function() {
$("#ajax-append").click(function() {
setInterval(function() {
var request = $.get("assets/replacecontent.jsp", function(html) {
alert(html);
$('#resDiv').html(html);
var newTableObject = document.getElementById("myTable");
alert(newTableObject);
sorttable.makeSortable(newTableObject);
// alert($("#myTable").length);
});
}, 3000);
});
});
Now if any time i sort the ajax response it get sorted but after another response it again change it's order but i want it sorted as previous one.
I think you should have read what the sorttable.js faq says:
Sorting the table when the page is loaded
Lots of people ask, "how do I make sorttable sort the table the first
time the page is loaded?" The answer is: you don't. Sorttable is about
changing the HTML that is served from your server without a page
refresh. When the page is first served from the server, you have to
incur the wait for it to be served anyway. So, if you want the table
sorted when a page is first displayed, serve the table in sorted
order. Tables often come out of a database; get the data from the
database in a sorted order with an ORDER BY clause in your SQL. Any
solution which involves you running sorttable as soon as the page
loads (i.e., without user input) is a wrong solution.
But they also state a solution for that:
//Find the TH you want to use, maybe you can store that using an event handler before
var myTH = document.getElementsByTagName("th")[0];
//Then sort it
sorttable.innerSortFunction.apply(myTH, []);
But to that you will have to find the column your user clicked on before, and to be honest I have not found any way using the sorttable api directly. Maybe use some kind of click event handler and store the th that was clicked last.

Insert an image depending on table content

I have a database item (called fairtrade) that has one of the following values: Yes, No, N/A.
These are displayed in the front end in a <table>.
<table class="data-table" id="product-attribute-specs-table">
<colgroup>
<col width="25%"></col>
</colgroup>
<tbody>
<tr class="last odd">
<th class="label">Fairtrade</th>
<td class="data last">N/A</td>
</tr>
</tbody>
</table>
If the database displays YES in the content I would like to display an image. If the database displays No or N/A I would like to hide that particular table row.
Can I use Javascript / JQuery to make the above happen. I'm not even sure if its possible.
Any help would be appreciated.
Well, you will need something like PHP to fetch the data from the database since JavaScript alone is not capable of doing that.
When that has been done you can use the server side language to insert the images depending on what data you get from the database while it's rendering the table.
If the table data is rendered for you you can use JavaScript to show the image depending on a value in a cell.
A simple jQuery example would probably be something like this (sorry, not tested, from the top of my head so might contain errors)
$("td").each(function(){
if($(this).text() == "YES"){
//code to show image here
}
});
Given your HTML, the following code should work for you.
$('.data-table tr .data').each(function() {
if ($(this).text() == 'Yes') {
// show your image
}
else {
$(this).closest('tr').hide();
}
});
Example fiddle

jQuery cleaning HTML table

This is my table:
<tr class=stuff>
<td id=id></td>
<td id=city_id></td>
<td id=temp></td>
<td id=date></td>
</tr>
This is my Javascript:
<script>
$(document).ready(function() { // waits when document is ready
$('.data').change(function() { // when dropbox value changes do this
getWeather(); // here I tried inserting table clearing code
});
});
function getWeather() {
$.getJSON('getTemperature/' + $('.data option:selected').val(), null, function(data) { // JSON request
$("#id").text(data.id); // changes fields accordingly
$("#city_id").text(data.city_id);
$("#temp").text(data.temperature);
$("#date").text(data.date);
});
}
</script>
Every item in dropdown menu does not have response from server, so I want it to clear the table just before making a new JSON request. So when JSON comes back with data, data is updated accordingly, but when JSON comes back with nothing, then all the tables will be empty.
At the moment when JSON retrieves no data, the old data still remains in the table.
I tried using $('.stuff').remove() and $('.stuff').clean() , but after using them right before getWeather(); then later I wasn't able to put info into table which I received from JSON. It just did not work anymore.
Feel free to ask any questions.
Try this
$('.stuff td').text("");
getWeather();
Depending how much of this sort of thing you will be doing on your site you might want to look into KnockoutJS, it is designed for dynamic displays with changing data, including auto hiding sections.

Categories

Resources