I am new in Bootstrap JS. I have a table made with Bootsrap JS, whose data came from a Json file. Here is The Code-
<div class="container-fluid">
<div class="row">
<div class="col-md-8">
<div class="fixedscroll">
<table id="user_table" class="table table-hover table-bordered table-striped responsive" style="margin-bottom: 0;" class="display">
<thead>
<tr>
<th>UID</th>
<th>Name</th>
<th>Address</th>
<th>Tags</th>
<th>Edit tags</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
function showAll(){
$.ajax({
url: "showAll",
dataType:"json",
success:function(data){
$('#user_table tr:gt(0)').remove();
jQuery.each(data['Payload'], function(index, value) {
var row = '<tr>'
+ '<td id="tduid">'+ value['uid']+ '</td>'
+ '<td>'+ value['name']+ '</td>'
+ '<td>'+ value['address']+ '</td>'
+ '<td>'+ value['tag1']+ ',' + value['tag2']+ ',' + value['tag3']+'</td>' + '<td>'+ '<button class="deleteUser btn btn-danger" type="submit">Edit</button>' + '</td></tr>';
$('#user_table').append(row);
});
}
});
Now This Payload is the name of my json, which came from a servlet where I call the database.
Now let, there is 3 tags. But some of rows have 2 tags. So, when I put the values in json the Json looks like-
{"Payload":[{"uid":"u01","name":"Subho","address":"Dumdum","tag1":"aircel","tag2":"vodafone","tag3":"airtel"},{"uid":"u02","name":"Jeet","address":"Baruipur","tag1":"airtel","tag2":"","tag3":"aircel"},{"uid":"u03","name":"Diba","address":"Jadavpur","tag1":"vodafone","tag2":"aircel","tag3":"airtel"},{"uid":"u04","name":"Tommy","address":"Baguihati","tag1":"aircel","tag2":"vodafone","tag3":""},{"uid":"u05","name":"Jonty","address":"Rahara","tag1":"","tag2":"vodafone","tag3":"airtel"},{"uid":"u06","name":"Gourav","address":"Tripura","tag1":"aircel","tag2":"vodafone","tag3":"airtel"}]}
Now You can see, that for UID=U02 there is 2 tags. And the output looks like picture attached. How can I remove the blank values or null values???? Please anyone help me...
I think, you are saying about the extra , in the tags column... one messy solution is
$.ajax({
url: "showAll",
dataType: "json",
success: function (data) {
$('#user_table tr:gt(0)').remove();
jQuery.each(data['Payload'], function (index, value) {
var tags = $.map([value.tag1, value.tag2, value.tag3], function (value) {
return value || undefined;
});
var row = '<tr>' + '<td id="tduid">' + value['uid'] + '</td>' + '<td>' + value['name'] + '</td>' + '<td>' + value['address'] + '</td>' + '<td>' + tags + '</td>' + '<td>' + '<button class="deleteUser btn btn-danger" type="submit">Edit</button>' + '</td></tr>';
$('#user_table').append(row);
});
}
});
As #Alnitak said
var tags = [value.tag1, value.tag2, value.tag3].filter(function (value) {
return value !== undefined;
});
console.log(tags)
Related
I am working with chrome extension .My main problem is I am not
able to append my tr under tbody as the error occur and stating
"Cannot read property 'getElementsByTagName' of null". So how Do I
append this in chrome extension using javascript.
In background.js I have tried this:
response.json().then(function (data) {
var dResponse = data.results;
if (dResponse.length > 0) {
var tableRef = document.getElementsByTagName('tbody')[0];
for (var obj = 0; obj < dResponse.length; obj++) {
var result = '<tr>' +
'<td>' + dResponse[obj].title + '</td>' +
'<td>' + dResponse[obj].category_path + '</td>' +
'<td>' + dResponse[obj].price + '</td>' +
'<td>' + dResponse[obj].num_favorers + '</td>' +
'<td>' + dResponse[obj].tags + '</td>';
result += '</tr>';
var tableRef =
tableRef.appendChild(result);
console.log(result);
};
}
});
I am hitting API and and my response is under data.
When I console my result so as output tr is comming.
var tableRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];
var tableRef = document.getElementsByTagName('tbody')[0];
both lines are giving this "Cannot read property 'getElementsByTagName' error
I also tried other ways to append but everytime it gives same error.I am not getting why this is happening.
response.json().then(function (data) {
var dResponse = data.results;
if (dResponse.length > 0) {
var tableRef = document.getElementsByTagName('tbody')[0];
for (var obj = 0; obj < dResponse.length; obj++) {
var result = '<tr>' +
'<td>' + dResponse[obj].title + '</td>' +
'<td>' + dResponse[obj].category_path + '</td>' +
'<td>' + dResponse[obj].price + '</td>' +
'<td>' + dResponse[obj].num_favorers + '</td>' +
'<td>' + dResponse[obj].tags + '</td>';
result += '</tr>';
var tableRef =
tableRef.appendChild(result);
console.log(result);
};
}
});
```
```background.html```
<div class="table-responsive mb-0" data-toggle="lists">
<table class="table table-sm table-nowrap card-table" id="myTable">
<thead>
<tr>
<th>Product Name</th>
<th>Category</th>
<th>Price</th>
<th>Favourites</th>
<th>Tags</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
```
<script src="background.js"></script>
> I am getting error "Cannot read property 'getElementsByTagName' of null". I only want to append my tr under tbody
I think that your background.js executes before the page has loaded, You can't access the "tbody"
This is how to run background.js after page load.
<script>
function init(){
var tag = document.createElement("script");
tag.src = "background.js";
document.getElementsByTagName("head")[0].appendChild(tag);
}
</script>
<head></head>
<body onload='init()'>
<table><tbody><tbody></table>
</body>
I have table rendered by js
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Город</th>
<th scope="col">Регион</th>
</tr>
</thead>
<tbody id="cities" style="overflow: auto;"></tbody>
Here is code
function GetCity() {
let citiesurl = '/cities/index';
$.ajax({
url: citiesurl,
contentType: 'application/json; charset=utf-8',
type: 'GET',
dataType: 'json',
processData: false,
success: function (data) {
$("#cities").empty();
var list = data;
for (var i = 0; i <= list.length - 1; i++) {
var tableData = '<tr>' + '<td>' +
(i + 1) +
'</td>' +
'<td class="cityId" style="display:none">' +
list[i].Id +
'</td>' +
'<td > ' +
list[i].Name +
'</td>' +
'<td > ' +
list[i].RegionName +
'</td>' +
'<td> ' +
'<button type="button" class="btn btn-info" onclick="DeleteCity()">' + 'Удалить' + '</button>' +
'</td>' +
'</tr>';
$('#cities').append(tableData);
}
}
})
}
I try to get value of cityId by button click.
Here is code
let id = $(this).closest('tr').find('.cityId').text();
But alert dhow me, that I get nothing.
Where is my error?
The problem is the context this which is not the clicked button.
Adopt the Event delegation approach for elements dynamically created:
$('#cities').on('click', 'button.btn', function() {...}
$("#cities").empty();
var list = [{
Id: 11,
Name: "Name",
RegionName: "RegionName"
}];
for (var i = 0; i <= list.length - 1; i++) {
var tableData = '<tr>' + '<td>' +
(i + 1) +
'</td>' +
'<td class="cityId" style="display:none">' +
list[i].Id +
'</td>' +
'<td > ' +
list[i].Name +
'</td>' +
'<td > ' +
list[i].RegionName +
'</td>' +
'<td> ' +
'<button type="button" class="btn btn-info">' + 'Удалить' + '</button>' +
'</td>' +
'</tr>';
$('#cities').append(tableData);
}
$('#cities').on('click', 'button.btn', function() {
let id = $(this).closest('tr').find('.cityId').text();
console.log(id)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Город</th>
<th scope="col">Регион</th>
</tr>
</thead>
<tbody id="cities" style="overflow: auto;"></tbody>
A better alternative is using the data-attributes
$("#cities").empty();
var list = [{
Id: 11,
Name: "Name",
RegionName: "RegionName"
}];
for (var i = 0; i <= list.length - 1; i++) {
var tableData = '<tr>' + '<td>' +
(i + 1) +
'</td>' +
'<td > ' +
list[i].Name +
'</td>' +
'<td > ' +
list[i].RegionName +
'</td>' +
'<td> ' +
'<button data-city-id="'+list[i].Id+'" type="button" class="btn btn-info">' + 'Удалить' + '</button>' +
'</td>' +
'</tr>';
$('#cities').append(tableData);
}
$('#cities').on('click', 'button.btn', function() {
let id = $(this).data('city-id');
console.log(id)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Город</th>
<th scope="col">Регион</th>
</tr>
</thead>
<tbody id="cities" style="overflow: auto;"></tbody>
You can modify you code the following way, using jquery:
$(document).ready(function() {
$('button').on('click', function() {
console.log($(this).data('city-id'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- // these are your buttons. -->
<button data-city-id="2">Delete</button>
<button data-city-id="3">Delete</button>
<button data-city-id="4">Delete</button>
You can generate buttons something like:
'<button type="button" class="btn btn-info" data-city-id="' + list[i].Id + '">' + 'Удалить' + '</button>'
Problem
Hi all, I am trying to refresh my table data on a set interval of 10 seconds... problem is that when I initially load the page there is a delay of 10 seconds before my table is shown...
Code
markup
<h2>Employee List</h2>
<!-- table -->
<table class="table table-striped table-hover table-responsive">
<thead>
<tr>
<td>ID</td>
<td>Emplyee Name</td>
<td>Address</td>
<td>Created at</td>
<td>Action</td>
</tr>
</thead>
<!-- table content dynamically generated by the javascript -->
<tbody id="showdata"></tbody>
<!-- end content -->
</table>
<!-- end table -->
jQuery
$(function(){
pollServer();
function pollServer(){
window.setTimeout(function () {
alert('hey');
$.ajax({ // this is a json object inside the function
type: 'ajax',
url: '<?php echo base_url('employee/showAllEmployee'); ?>',
async: false,
dataType: 'json',
success: function(data){
console.log(data);
var html = '';
var i;
for(i = 0; i < data.length; i++){
html += '<tr>' +
'<td>' + data[i].employee_id + '</td>' +
'<td>' + data[i].employee_name + '</td>' +
'<td>' + data[i].address + '</td>' +
'<td>' + data[i].created_at + '</td>' +
'<td>' +
'<div class="pull-right">' +
'<a class="btn btn-info btn-xs item-edit" href="javascript:;" data="' + data[i].employee_id + '">Edit</a>' +
'<a class="btn btn-danger btn-xs item-delete" href="javascript:;" data="' + data[i].employee_id + '"><i class="fa fa-times"></i></a>' +
'</div>' +
'</td>' +
'</tr>'
}
$('#showdata').html(html);
},
error: function(){
alert('Could not get Data from Database');
},
complete: function(){
pollServer();
}
})
}, 10000);
}
});
Question
How do I get my data on page load, and then ping the server every 10 seconds thereafter?
change pollServer as follows
function pollServer(){
$.ajax({ // this is a json object inside the function
// removed for clarity
complete: function(){
setTimeout(pollServer, 10000);
}
});
}
Just call the same function inside it's success callback with a timeout.
function pollServer() {
$.ajax({
...
success: function(data) {
setTimeout(function() {
pollServer();
},10000);
}
});
}
// Call the function on load
pollServer();
I have a (heavy) function that fetches some data from php/sql and then render it in html. When I load the page for the first time I call this function and everything is fine. When I click on a button I call this function also after an successfull other ajax call, but then my browsers freezes and crashes. I get in Firefox and Chrome an error (page unresponsive).
Here the (heavy)function:
function getMinerAttributesByType(type) {
$.ajax({
type : "POST",
url : "/app/ajax/DataminerAjax.php",
dataType: "json",
timeout : 8000,
data : {getMinerAttributesByType:type}
}).success(function(json){
$tableConfigured = $("#keywordsgroupsConf tbody");
$tableConfigured.html("");
$tableUnconfigured = $("#keywordsgroups tbody");
$tableUnconfigured.html("");
$.each(json, function(key, value){
var $table;
if (value.configured == 0) {
$table = $tableUnconfigured;
} else {
$table = $tableConfigured;
}
$table.append('<tr>' +
'<td>' + value.name + '</td>' +
'<td><button class="btn btn-info" data-toggle="collapse" data-target="#'+ value.id+'-subs" data-id="'+ value.id +'" data-init="0">Config</button></td>' +
'</tr>' +
'<tr class="dataset">' +
'<td colspan="2" class="subrow">' +
'<div style="background:#eee;" class="accordian-body collapse" id="'+ value.id+'-subs">' +
'<table style="margin-bottom: 10px;" class="table" id="table-' + value.id + '" data-id="' + value.id + '">'+
'<tbody>' +
'</tbody>' +
'</table>'+
'<div style="margin-left:10px;" class="input-append">'+
'<input type="text" placeholder="Keywordgroup name">'+
'<button class="btn btn-create-keywordgroup" data-id="' + value.id + '"><i class="icon icon-plus"></i> Add</button>'+
'<button class="btn btn-success btn-mark-as-c" data-id="' + value.id + '"><i class="icon-white icon-check"></i> Mark as configured</button>' +
'</div>' +
'</div>' +
'</td>'+
'</tr>');
});
});
}
Here the function that call the function and crashes afterwards:
$(document).on("click", ".btn-mark-as-c", function(){
if (confirm("Are you sure you want to mark this attribute as configured?")) {
$this = $(this)
var id = $this.attr("data-id");
$.ajax({
type : "POST",
url : "/app/ajax/DataminerAjax.php",
dataType: "json",
data : {updateMinerAttributeState:id, state:1}
}).success(function(json){
if (json.status == "success") {
// crashes here in this call of the heavy function
getMinerAttributesByType(1);
} else {
alert("There was an error!");
}
});
}
});
Someone a pointer?
I dont have 50 rep so I cant comment yet buuuut, couldn't you bust out that chunk of HTML formatting to a PHP document, and then use the AJAX to call the PHP and return the result? Then use $table.append(result)?
Ex)
<script type="text/javascript">
jQuery(document).on('click', '.menuItem', function()
{
event.preventDefault();
var mainCategory = $(this).attr('id').split('xx')[0];
$.ajax({
url: '/php/SubMenuBar.php', <----- Access the PHP file.
data: {
MainCategory: mainCategory, <---- Parameters for the PHP file (declared using $_GET() in the PHP file)
},
success: function(result) <--- Result becomes the output from the PHP file
{
$table.append(result);
}
});
Instead of appending the rows to the DOM one at a time, concatenate them into a string and then add them all at once.
function getMinerAttributesByType(type) {
$.ajax({
type : "POST",
url : "/app/ajax/DataminerAjax.php",
dataType: "json",
timeout : 8000,
data : {getMinerAttributesByType:type}
}).success(function(json){
var $tableConfigured = $("#keywordsgroupsConf tbody");
var $tableUnconfigured = $("#keywordsgroups tbody");
var rowsConfigured = '', rowsUnconfigured = '';
$.each(json, function(key, value){
var row = '<tr>' +
'<td>' + value.name + '</td>' +
'<td><button class="btn btn-info" data-toggle="collapse" data-target="#'+ value.id+'-subs" data-id="'+ value.id +'" data-init="0">Config</button></td>' +
'</tr>' +
'<tr class="dataset">' +
'<td colspan="2" class="subrow">' +
'<div style="background:#eee;" class="accordian-body collapse" id="'+ value.id+'-subs">' +
'<table style="margin-bottom: 10px;" class="table" id="table-' + value.id + '" data-id="' + value.id + '">'+
'<tbody>' +
'</tbody>' +
'</table>'+
'<div style="margin-left:10px;" class="input-append">'+
'<input type="text" placeholder="Keywordgroup name">'+
'<button class="btn btn-create-keywordgroup" data-id="' + value.id + '"><i class="icon icon-plus"></i> Add</button>'+
'<button class="btn btn-success btn-mark-as-c" data-id="' + value.id + '"><i class="icon-white icon-check"></i> Mark as configured</button>' +
'</div>' +
'</div>' +
'</td>'+
'</tr>';
if (value.configured == 0) {
rowsUnconfigured += row;
} else {
rowsConfigured += row;
}
});
$tableConfigured.html(rowsConfigured);
$tableUnconfigured.html(rowsUnconfigured);
});
}
I'm creating a 'live' leaderboard table. Every X seconds, an AJAX request is sent to the server to load the latest leaderboard data.
If there's a change in data, the leaderboard will instantly update upon the AJAX request.
However - If there IS a change, instead of instantly showing the new data, I want to animate the table row to its new position instead of instantly reloading it. What is the best way of achieving something like this?
I'm updating the leaderboard at the moment like so:
$(document).ready(function() {
showLeaderboard();
if (autoUpdate != false) {
window.setInterval(function(){
$('#wrapper h2, #leaderboard tbody tr').remove(updateLeaderboard());
}, reloadInterval);
}
});
function updateLeaderboard() {
leaderBoardType;
numRecords;
quizIDs;
topListTitle;
latestTitle;
$.webMethod({
url: 'xxx',
data: '{quizIDs:"'+quizIDs+'",numRecords:"'+numRecords+'"}',
type: 'POST',
cache: false,
beforeSend: function () {
$('body').append('<div class="loading"></div>');
},
success: function (ret)
{
$('.loading').remove();
$('#wrapper').prepend(topListTitle);
$.each(ret.leaderboard,function(i){
pos = i + 1;
str = '<td class="position">' + pos + '</td>';
str += '<td class="name">' + ret.leaderboard[i].first_name + ' ' + ret.leaderboard[i].last_name + '</td>';
str += '<td class="time">' + getTime(ret.leaderboard[i].time_taken) + '</td>';
str += '<td class="points">' + ret.leaderboard[i].points + '</td>';
//str += '<td>' + ret.leaderboard[i].last_name + '</td>';
//str += '<td>' + ret.leaderboard[i].incorrect_attempts + '</td>';
//str += '<td>' + ret.leaderboard[i].user_id + '</td>';
$('#leaderboard tbody').append('<tr>'+str+'</tr>');
});
},
error: function (response) { alert(response.responseText); }
});
}
HTML
<table id="leaderboard">
<thead>
<tr>
<th class="position">Position</th>
<th class="name">Name</th>
<th class="time">Time Taken</th>
<th class="points">Points</th>
</tr>
</thead>
<tbody>
</tbody>
</table>