$(document).ready() makes datatable not work properly - javascript

I'm trying to start the table empty with no data in <tbody> and choose some parameters send to the server via $.getJSON and append the returned json data inside <tbody>.
But it looks like because of the $(document).ready() it makes it not work properly, the pagination and the search stop working completely.
BTW, I'm including all the needed files, I know that the error is because I'm populating the table after the page loads, I just would like to know if there is another approach to solve this problem.
Here is my code:
<script type="text/javascript" src="../js/jquery.dataTables.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#contacts').dataTable({
"sPaginationType" : "full_numbers"
});
$("#submit").click(function()
{
$.getJSON("/myurl",
function(data)
{
$("#table_body").empty();
$.each(data, function(i, item)
{
$("#table_body").show("slow");
$("#table_body")
.append(
'<tr class="gradeC">' +
'<td>' + item.name+ '</td>' +
'<td>' + item.birthdate + '</td>' +
'<td>' + item.age + '</td>' +
'</tr>'
);
});
});
});
});
</script>
<!-- NOW THE HTML CODE FOR THE TABLE -->
<table cellpadding="0" cellspacing="0" border="0" class="display" id="contacts">
<thead>
<tr>
<th>Name</th>
<th>Birthdate</th>
<th>Age</th>
</tr>
</thead>
<tbody id="table_body"></tbody>
<tfoot>
<tr>
<th>Name</th>
<th>Birthdate</th>
<th>Age</th>
</tr>
</tfoot>
</table>

It doesn't appear that you are using the Datatables API properly. Read through the documentation and try using the datatables methods for adding rows and emptying the table, etc.

Try using the $(function() { ... }); syntax instead. I recently had an issue where $(document).ready(function() { ... }); wasn't working. I tried the newer syntax and it fixed it...
Hope this helps.

fnAddData() should not be used for loading entire content row by row. To table content from JSON you can set this url in the sAjaxSource property and define mappings between JSON properties and columns. See examples on:
http://datatables.net/release-datatables/examples/ajax/objects.html
http://datatables.net/release-datatables/examples/ajax/deep.html
I believe that your approach works, but take a look on this pages too maybe it would be easier to load them this way.
Jovan

Related

Split one big table into multiple tables based on content of acolumn in each row

I looked at previous similar questions and only found one answer with the following code splitting the data into 2 tables:
// ==UserScript==
// #name TABLE SPLITTER
// #namespace http://www.w3schools.com/
// #description DESCRIPTION!!!
// #include http://www.w3schools.com/css/css_table.asp
// #require http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// #require https://raw.github.com/tomgrohl/jQuery-plugins/master/jcookie/script/jquery.jcookie.min.js
// #version 1
// ==/UserScript==
$(function(){
// YOUR JAVASCRIPT CODE HERE
// YOU HAVE JQUERY INCLUDED
setTimeout(function(){
var mainTable = $("table");
var splitBy = 3;
var rows = mainTable.find ( "tr" ).slice( splitBy );
var secondTable = $("<table id='secondTable' style='background:pink;'><tbody></tbody></table>").insertAfter("table");
secondTable.find("tbody").append(rows);
console.log(secondTable);
mainTable.find ( "tr" ).slice( splitBy ).remove();
}, 3000);
});
I am looking for something like this that will split the information to tables base on the amount of different options i have.
ultimately i would like something like:
Goal
Or even better remove the type from the output and have it show before each of the new tables like this: option 2
Not sure if that even possible and would love some help.
This is not the optimal solution, you can get the idea and improve it.
Read JS comments.
var dynamicData = $('#dynamicData'); // To identify the parent that we will append data to.
$(document).ready(function(){
$('.types').each(function(){ // loop on each type and check if that type not appended inside '#dynamicData' as 'h5', if no,t append it and append a table related to it
var name = $.trim($(this).text());
var check = $('h5#i_' + name , dynamicData).length;
if (check === 0){
$(dynamicData).append('<h5 id="i_' + name + '">' + name + '</h5>');
$(dynamicData).append('<table id="t_' + name + '" class="table table-hover table-striped table-bordered"></table>');
$('table#t_' + name).append('<thead>'+
'<tr>'+
'<th>Product</th>'+
'<th>Price</th>'+
'</tr>'+
'</thead>'+
'<tbody>'+
'</tbody>');
}
});
$('#allContent > tr').each(function(){ // loop on each row in '#allContent' and read '.types' class, then clone this row and remove the type then append it inside the target table using id
var name = $.trim($('.types',this).text());
$(this).clone().find('.types').remove().end().appendTo('table#t_' + name + ' > tbody');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<h4 class="text-center text-danger">Before:</h4>
<table class="table table-hover table-striped table-bordered">
<thead>
<tr>
<th>Product</th>
<th>Price</th>
<th>Type</th>
</tr>
</thead>
<tbody id="allContent">
<tr>
<td>TV</td>
<td>250$</td>
<td class="types">Product</td>
</tr>
<tr>
<td>Channel</td>
<td>1$</td>
<td class="types">Service</td>
</tr>
<tr>
<td>Channel</td>
<td>1$</td>
<td class="types">Service</td>
</tr>
<tr>
<td>DVD</td>
<td>14$</td>
<td class="types">Product</td>
</tr>
<tr>
<td>Support</td>
<td>15$</td>
<td class="types">Team</td>
</tr>
</tbody>
</table>
<h4 class="text-center text-danger">After:</h4>
<div id="dynamicData"></div>
My first thought is make a unique list of the types. Then loop over that list, cloning the original table for each. Then loop through the cloned table and remove everything that you don't want there. Definitely not the most efficient, but it's simple and it works.
let types = [... new Set($('table.original tr td:last-of-type')
.get().map(type => type.textContent))];
//create a container for the cloned tables
$('table.original').after(`<h4>After:</h4><div class="cloned-tables"></div>`)
//loop over types, clone tables, modify accordingly
$.each(types, function(index, type) {
$(`<p class="type">${type}</p>${$('table.original')[0].outerHTML}`)
.appendTo('.cloned-tables')
.find('tr td:last-of-type').each(function() {
if (this.textContent !== type) { this.parentElement.remove(); }
this.remove();
});
});
//remove all type header cells
$(`.cloned-tables table th:last-of-type`).remove();
h4{color: red;}
.type{color: blue;}
<h4>Before:</h4>
<table class="original">
<thead>
<tr>
<th>Product</th>
<th>Price</th>
<th>Type</th>
</tr>
</thead>
<tbody>
<tr>
<td>TV</td>
<td>$250</td>
<td>Product</td>
</tr>
<tr>
<td>Channel</td>
<td>$1</td>
<td>Service</td>
</tr>
<tr>
<td>Channel</td>
<td>$1</td>
<td>Service</td>
</tr>
<tr>
<td>DVD</td>
<td>$14</td>
<td>Product</td>
</tr>
<tr>
<td>Support</td>
<td>$15</td>
<td>Team</td>
</tr>
</tbody>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Another thought on using greasemonkey, make sure that the table exist and is populated before you try and do anything with it. Greasemonkey is in a different scope than the original code, so document.ready() is inaccurate. Sometimes things load very asychronously, which will make valid code seem broken. I tend to do something like this:
let loading = setInterval(function() {
if ($('table.original').length) {
clearInterval(loading);
//greasmonkey code here
}
}, 1000);

Retrieve data from all users then show their user ID in a html table and update via button

I want to have a table like this
which will get data from the firebase database, here is my firebase database structure for requests .
Here's my code which I tried to edit from a previous question, but as you can see from the table above the data says undefined.
<table class="table table-striped" id="ex-table">
<thead class="thead-inverse">
<tr>
<th>ID Number</th>
<th>Request Status</th>
</tr>
</thead>
<tbody>
<tr id="tr">
<td id="status"></td>
</tr>
</tbody>
<script>
var database = firebase.database().ref().child('Request');
database.once('value', function(snapshot){
if(snapshot.exists()){
var content = '';
snapshot.forEach(function(data){
var status= data.val().status;
content += '<tr>';
content += '<td>' + status + '</td>';//column2
content += '</tr>';
});
$('#ex-table').append(content);
}
});
</script>
This is for my admin panel which approves the requests of the users, also how can I do the approval using 2 buttons named Approve and Deny?
Sorry for the inconvenience I am new to firebase.
Thank you very much!
I have used a keyword named status inside my firebase database. I replaced it and then boom it worked like a charm. I am very sorry for wasting your time.

Adding id to dynamically generated table before appending to div

I am creating a table as below in my Javascript:
var l_table = op.script.table_dom_start + op.script.l_table_header + l_table_rows + op.script.table_dom_end;
Which results in:
<table class="table table-hover">
<tr>
<th class="capitalize">
...
</th>
</tr>
</table>
Which is then appended to target div:
$(l_table).appendTo('#l-ajax-response-div');
Now, before appending, I want to give this class an id and tried below ways:
$(l_table).attr('id', 'l-entry-table');
and
l_table.id='l-entry-table';
Both of these fail to work, what is going on here?
Variable contents:
table_dom_start: '<table class="table table-hover">',
header: specific header for that table
row: specific rows for that table
table_dom_end: '</table>',
Try something like this:
var mytable=$(l_table);
mytable[0].id="l-entry-table";
mytable.appendTo('#l-ajax-response-div');
Check this below example it will alert no of tables found by id.
var l_table = '<table class="table table-hover"><tr><th class="capitalize">Table with ID</th></tr></table>';
$(l_table).attr('id', 'l-entry-table').appendTo('#l-ajax-response-div');
alert($('#l-entry-table').length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="l-ajax-response-div"></div>

Lightbox not showing Jquery

I am trying to show a popover upon a link being selected in my HTML table.
Here is my table:
<table width="1150" border="0" cellspacing="0" cellpadding="0">
<tr class="inner1-top">
<td class="name">NAME</td>
<td class="company">COMPANY</td>
<td class="position">POSITION</td>
<td class="mc">MC #</td>
<td class="dot">DOT #</td>
</tr>
<tr class="inner2-top">
</tr>
</table>
I fill that table using the following Javascript:
$('.inner2-top').append('<tr><td class="name"><a href="#">'+
object.get('username') + '</a></td><td class="company">' +
object.get('company') + '</td><td class="position">' +
object.get('position') + '</td><td class="mc">' +
object.get('mc') + '</td><td class="dot">' +
object.get('dot') + '</td><td>');
})(jQuery);
I am trying to make it so when the name is clicked my popover will show:
$(document).ready(function(){
$('.name1 a').click(function(e) {
$('.popup1').lightbox_me({
});
Unfortunately this does not work. Any ideas?
In order to use document.on to bind jQuery events to dynamically added elements, working with your existing structure, try the following:
$(document).ready(function(){
$(document).on('click', '.name a', (function(e) {
e.preventDefault();//to prevent the browser from following the link or reloading the page
$('.popup1').lightbox_me({
//whatever other code is necessary for your lightbox
});
)};
jQuery documentation

Use greasemonkey to add HTML before table

I am using greasemonkey to edit a page. I need to add my own table between the two tables that are already on the page and then remove the second table. There is nothing really setting the two existing tables apart, so I am having trouble with the function to insertBefore.
<h3>Table 1</h3>
<table class="details" border="1" cellpadding="0" cellspacing="0">
<tbody><tr>
<th>1</th>
<td>2</td>
</tr>
</tbody></table>
<h3>Table 2</h3>
<table class="details" border="1">
<tbody><tr>
<th>1</th>
<td>2</td>
</tr><tr>
<th>3</th>
<td>4</td>
</tr>
</tbody></table>
I have found the below code helpful in removing table 2, but I need to add my own table before table 2 first:
// find second <table> on this page
var xpathResult = document.evaluate('(//table[#class="details"])[2]', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
var node=xpathResult.singleNodeValue;
// now hide it :)
node.style.display='none';
This is a good chance to introduce jQuery. jQuery will be dead useful for the other things your GM script will do, plus, it's robust and cross-browser capable (for reusing your code).
(1) Add this line to the Greasemonkey metadata section, after the // #include directive(s):
// #require http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js
(Note you may have to uninstall and then reinstall the script to get jQuery copied over.)
(2) Then you can use this code to add your table and delete the old one:
//--- Get the 2nd table with class "details".
var jSecondTable = $("table.details:eq(1)");
//--- Insert my table before it.
jSecondTable.before
(
'<table id="myTable">'
+ ' <tr>'
+ ' <th></th>'
+ ' <th></th>'
+ ' </tr>'
+ ' <tr>'
+ ' <td></td>'
+ ' <td></td>'
+ ' </tr>'
+ '</table>'
);
//--- Delete the undesired table.
jSecondTable.remove ();
/*--- Alternately, just hide the undesired table.
jSecondTable.hide ();
*/
You can see a version of this code, in action, at jsFiddle.
Alternate method of adding your table -- Less straightforward but does not require all the quotes:
jSecondTable.before ( (<><![CDATA[
<table id="myTable">
<tr>
<th></th>
<th></th>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</table>
]]></>).toString ()
);

Categories