Render big list into table using Jquery - javascript

I am having a big list which I am grouping into a size of 500 and then rendering them one at a time to client on demand. I am using the following Java script code to render the list into table.
var counter;
$(document).ready(function() {
var table = $('#example').DataTable();
$('#example tbody').on('click', 'tr', function() {
$(this).toggleClass('selected');
});
$('#button').click(function() {
alert(table.rows('.selected').data().length + ' row(s) selected');
});
});
function getData(submit) {
var pointer;
var msg = "";
var company = "";
if (submit == 1) {
//On click of get more
counter += 500;
pointer = counter;
} else {
//On load
counter = 500;
pointer = 500;
}
$.ajax({
type: "GET",
url: "/biz/getListOfFreeMembers",
data: {
limit: pointer
},
success: function(data) {
$.each(data, function(i, obj) {
var t = $('#example').DataTable();
t.row.add([
obj.companyName,
obj.mobileNo,
obj.companyWebsite,
obj.firstName,
obj.address,
obj.createDate
]).draw();
});
},
error: function(e) {
alert("error" + e.Message);
}
});
}
<link href="//cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<div id="demo" class="col-sm-12">
<div class="table-responsive">
<table id="example" class="table">
<thead>
<tr>
<th>Company Name</th>
<th>Mobile Number</th>
<th>Website</th>
<th>Person Name</th>
<th>Address</th>
<th>Date of Creation</th>
</tr>
</thead>
<tbody id="list_of_users">
</tbody>
</table>
</div>
</div>
Get more data
The table is rendering correctly for the first time, but when I click the Get more data link, the new set of data is not appending to the existing set, instead the new set is getting displayed first and then the old set and so on for each click of get more data. Please suggest a way for appending the new data set to the old one in the table. Thank you.

Your code is working fine. (check this codePen)
May be you are missing, that Page Numbers are increasing (meaning new data is going on the next pages)
Or May be your service is not responding the data (Check the Network Console)
var counter=0;
var t=null;
var url = 'tableData';
$(document).ready(function() {
t = $('#example').DataTable();
t
.column( '0:visible' )
.order( '' )
.draw();
$('#example tbody').on('click', 'tr', function() {
$(this).toggleClass('selected');
});
$('#button').click(function() {
alert(t.rows('.selected').data().length + ' row(s) selected');
});
getData();
});
function getData(submit) {
$('#loading').show();
var pointer=0;
var msg = "";
var company = "";
if (submit == 1) {
//On click of get more
counter += 500;
pointer = counter;
url = 'tableData2';
} else {
//On load
counter = 500;
pointer = 500;
url = 'tableData';
}
$.ajax({
contentType: "application/json",
type: "GET",
url: "http://demo2315600.mockable.io/" + url,
success: function(data) {
$('#loading').hide();
//alert('asd');
$.each(data, function(i, obj) {
t.row.add([
obj.companyName,
obj.mobileNo,
obj.companyWebsite,
obj.firstName,
obj.address,
obj.createDate
]).draw();
});
},
error: function(e) {
alert("error" + e.Message);
}
});
}
<link href="//cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<div id="demo" class="col-sm-12">
<div class="table-responsive">
<table id="example" class="table">
<thead>
<tr>
<th>Company Name</th>
<th>Mobile Number</th>
<th>Website</th>
<th>Person Name</th>
<th>Address</th>
<th>Date of Creation</th>
</tr>
</thead>
<tbody id="list_of_users">
</tbody>
</table>
</div>
</div>
Get more data
<span id="loading" style="display:none;">pleas wait Load Data</span>

Related

Editable bootstrap table then Insert data to MYSQL database

I'm trying to use an editable bootstrap table where in data can be inserted on the database. However, I find it difficult since I'm only new with this field. I can load the data from the database and edit the table field but I don't know how can I insert it on the database.
Below is my code for the table. For the <tbody, I used javascript and ajax to load the data from the database. Note that, it only loads the CATEGORY ID and DESCRIPTION. The AMOUNT must be inserted by the user.
<div id="table" class="table-editable">
<table class="table table-sm table-striped table-hover" id="tbl-fees">
<thead>
<tr>
<th>CATEGORY</th>
<th style="display:none">CATEGORY ID</th>
<th scope="col">DESCRIPTION</th>
<th scope="col" class="text-right">AMOUNT</th>
</tr>
</thead>
<tbody id= "fees_table"></tbody>
</table>
</div>
As per the resources online, it says that I can use contenteditable="true" for me to have an editable table.
<script>
function load_fees_list()
{
var sy_id=2;
$.ajax({
method:"GET",
url: "<?php echo site_url(); ?>Get-FCP/"+sy_id,
success: function(response){
$.each(response.fcp_data, function(key, value){
$('#fees_table').append('<tr>\
<td style="display:none">'+value["fc_desc"]+'</td>\
<td id="fc_id">'+value["fc_id"]+'</td>\
<td id="fcp_description">'+value["fcp_description"]+'</td>\
<td id="fmf_amount" class="text-right" contenteditable="true">'+0+'</td>\
</tr>');
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("Status: " + textStatus);
console.log("Error: " + errorThrown);
}
});
}
</script>
I found a script online where it shows the output of the live table when button is clicked.
var $TABLE = $('#table');
var $BTN = $('#export-btn');
var $EXPORT = $('#export');
// A few jQuery helpers for exporting only
jQuery.fn.pop = [].pop;
jQuery.fn.shift = [].shift;
$BTN.click(function () {
var $rows = $TABLE.find('tr:not(:hidden)');
var headers = [];
var data = [];
// Get the headers (add special header logic here)
$($rows.shift()).find('th:not(:empty)').each(function () {
headers.push($(this).text().toLowerCase());
});
// Turn all existing rows into a loopable array
$rows.each(function () {
var $td = $(this).find('td');
var h = {};
// Use the headers from earlier to name our hash keys
headers.forEach(function (header, i) {
h[header] = $td.eq(i).text();
});
data.push(h); //adds new items to the end of an array
});
// Output the result
$EXPORT.text(JSON.stringify(data));
});
However, I can't insert it on the database. I'm planning of inserting the data in a new MySQL table in which it stores the description and amount. Can someone help me on how can I insert it?

Displaying data in table(view) passed from Controller - Codeigniter

I want to display data in table on inserting data as well as when the page is loaded. Storing data successfully works with the code but the issue is;
When I use POST, the form data is completely visible in the URL.
How do i display all data passed in json format in html table.
HTML:
<table class="table table-striped table-bordered" id="myTable">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Match</th>
<th scope="col">Match Date</th>
<th scope="col">Winner</th>
<th scope="col">Loser</th>
<th scope="col">Man of the Match</th>
<th scope="col">Bowler of Match</th>
<th scope="col">Best Fielder</th>
</tr>
</thead>
</table>
JAVASCRIPT:
<script>
$(function() {
$("#submit").on("click", function(e) {
var team_one = $('#team_one').val();
var team_two = $('#team_two').val();
var match_summary = $('#match_summary').val();
var match_date = $('#match_date').val();
var winner = $('#winner').val();
var loser = $('#loser').val();
var man_of_the_match = $('#man_of_the_match').val();
var bowler_of_the_match = $('#bowler_of_the_match').val();
var best_fielder = $('#best_fielder').val();
$.ajax(
{
type: "POST", //HTTP POST Method
url: '<?php echo base_url(); ?>/MatchController/storeMatch',
data: { //Passing data
'team_one': team_one,
'team_two': team_two,
'match_summary' : match_summary,
'match_date' : match_date,
'winner' : winner,
'loser' : loser,
'man_of_the_match' : man_of_the_match,
'bowler_of_the_match' : bowler_of_the_match,
'best_fielder' : best_fielder
},
success: function (response) {
console.log("Response: " + response);
alert("Data stored successfully");
},
});
});
});
//FETCH ALL MATCH DATA USING PASSED API IN CONTROLLER
$(document).ready(function (){
getData();
function getData(){
$.ajax({
url : "<?php echo base_url(); ?>/MatchController/fetchMatchData",
method : 'get',
dataType: "json",
success: function(data){
}
});
}
});
CONTROLLER:
public function storeMatch()
{
$team_one = $_POST['team_one'];
$team_two = $_POST['team_two'];
$match_date = $_POST['match_date'];
$match_summary = $_POST['match_summary'];
$winner = $_POST['winner'];
$loser = $_POST['loser'];
$man_of_the_match = $_POST['man_of_the_match'];
$bowler_of_the_match = $_POST['bowler_of_the_match'];
$best_fielder = $_POST['best_fielder'];
$data = array(
'team_one' => $team_one,
'team_two' => $team_two,
'match_date' => $match_date,
'match_summary' => $match_summary,
'winner' => $winner,
'loser' => $loser,
'man_of_the_match' => $man_of_the_match,
'bowler_of_the_match' => $bowler_of_the_match,
'best_fielder' => $best_fielder
);
$this->MatchModel->saveMatchData($data);
}
public function fetchMatchData()
{
$match_data = $this->MatchModel->fetchMatchList();
return $match_data;
}
Try to pass the result to <tbody> use JQuery
success: function(data){
//delete old tbody block
$('#myTable tbody').remove()
//add tbody block
$('#myTable').append('<tbody><tr><td>'+data.someValue+'</td></tr></tbody>')
}
And when you want add new data just call your getData().
success: function (response) {
getData()
console.log("Response: " + response);
alert("Data stored successfully");
},
Also look at e.preventDefault for your ajax call. If you use ajax needlessly reload page

Two different table with 2 different AJAX JSON response data

I'm new to javascript.
I need to fetch JSON response from 2 different AJAX request and create a 2 different table.
I have achieved it for 1 JSON response and 1 Table.
HTML :
<div style="width:700px;padding:20px;S">
<table id="host_table" class="table">
<tr>
<th>Server Name</th>
<th>Availability %</th>
</tr>
</table>
</div>
JavaScript :
$(function() {
// kick off with fetchdata
fetchData();
// fetchServiceData();
});
function make_base_auth(user, password) {
var tok = user + ':' + password;
var hash = btoa(tok);
return 'Basic ' + hash;
}
function fetchData() {
var time = new Date();
var end = Math.floor((new Date).getTime()/1000);
//var end = ~~(Date.now() /1000) ;
var start = Math.floor(time.setDate(time.getDate() - 1)/1000);
Availreport = "http://xx.xx.xx.xx/nagios/cgi-bin/archivejson.cgi?query=availability&availabilityobjecttype=hostgroups&hostgroup=ALM&assumedinitialhoststate=up&assumedinitialservicestate=ok&starttime=" + start + "&endtime=" + end;
$.ajax({
type: "GET",
url: Availreport,
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization',
make_base_auth("nagiosadmin", "nagiosadmin"));
},
dataType: 'json', //data format
//async: false,
//success: onOutboundReceived //on receive of reply
timeout: 0,
success: availshow
});
function availshow(series) {
// 1. remove all existing rows
$("tr:has(td)").remove();
$.each(series.data.hostgroup.hosts, function (index, test) {
$('<tr>').append(
$('<td>').text(test.name),
$('<td>').text(parseInt(((test.time_up - test.time_down)/test.time_up)*100)),
).appendTo('#host_table');
});
$('#host_table tr').each(function() {
var $td = $(this).find('td:eq(1)');
var value = $td.text();
if (parseInt(value) < 100) {
$td.css('background-color', 'red');
}
});
}
This works perfect for 1 table creation.
But I'm unable to proceed for 2 table creation for 2 JSON response.
I can able to create 2 tables in HTML.
But unable to feed the JSON response to specific table.
HTML for 2 table Creation :
<table id="host_table" class="inlinetable" style="display: inline-block;">
<tr>
<th>Server Name</th>
<th>Availability %</th>
</tr>
</table>
<table id="service_table" class="inlinetable" style="display: inline-block;">
<tr>
<th>Service Name</th>
<th>Availability %</th>
</tr>
</table>
How to achieve my task?
make tables side by side like this
its another question but
use for first table
style="display: inline-block;"
and for second table
style="float: left;">
<table id="host_table" class="inlinetable" style="display: inline-block;">
<thead>
<tr>
<th>Server Name</th>
<th>Availability %</th>
</tr>
</thead>
<tbody></tbody>
</table>
<table id="service_table" class="inlinetable" style="float: left;">
<thead>
<tr>
<th>Service Name</th>
<th>Availability %</th>
</tr>
</thead>
<tbody></tbody>
</table>
JS
$(function() {
// kick off with fetchdata
// service_table();
service_table();
// host table();
fetchData2();
});
function service_table() {
$.ajax({
type: "GET",
url: Availreport,
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization',
make_base_auth("nagiosadmin", "nagiosadmin"));
},
dataType: 'json',
timeout: 0,
success:function(series) {
$('#service_table tbody').empty();
// your row loop code
}
});
function service_table() {
$.ajax({
type: "GET",
url: Availreport,
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization',
make_base_auth("nagiosadmin", "nagiosadmin"));
},
dataType: 'json',
timeout: 0,
success:function(series) {
$('#host_table tbody').empty();
// your row loop code
}
});
}
its just how it can work for your understanding, more dynamic solution can be made

Updating the values attribute of a table inside a JSP page after an AJAX call

I have problem in displaying the content of a table which will be available once an AJAX request is made on click of some row of another table in the same page.
Following is my code for the table in my JSP page.
<table id="previousList" class="table">
<thead>
<tr>
<th colspan="6">Previous Billing Records</th>
</tr>
<tr>
<th>Bill Number</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<c:forEach var="lastBill" items="${previousBills}" varStatus="status">
<tr>
<td>${lastBill.billingId}</td>
<td>${lastBill.billAmount}</td>
</tr>
</c:forEach>
</tbody>
</table>
var jsonData;
var patientTable = $('#patientsList').DataTable();
var table = document.getElementById("selectedPatient");
$('#patientsList tbody').on('click', 'tr', function() {
var data = patientTable.row(this).data();
console.log("Data " + data);
$.ajax({
type: "POST",
url: "/LoginMavenSpringMVC/billing/lastBill",
data: "patientId=" + data[0],
success: function(response) {
console.log("Showing the LastBill Details: " + response);
jsonData = response;
},
error: function(e) {
alert('Error: ' + e);
}
});
});
My controller code is as follows.
#RequestMapping(value="/lastBill")
public #ResponseBody String lastBill(ModelMap model, String patientId)
{
System.out.println("ID: " + patientId);
Gson gson = new Gson();
Bill b = new Bill();
b.setBillAmount(1000);
b.setBillingId("12345SDf");
Collection<Bill> bills = new ArrayList<Bill>();
bills.add(b);
model.addAttribute("previousBills",bills);
String jsonBills = gson.toJson(bills);
model.addAttribute("jsonBills", jsonBills);
return jsonBills;
}
I am able to get the JSON data but failed to bind the values to the table. Any suggestions/answers would be appreciable. Thanks in advance.
try this it should work.
var jsonData;
$('#patientsList tbody').on('click', 'tr', function() {
var data = patientTable.row(this).data();
console.log("Data " + data);
$.ajax({
type: "POST",
url: "/LoginMavenSpringMVC/billing/lastBill",
data: "patientId=" + data[0],
success: function(response) {
console.log("Showing the LastBill Details: " + response);
jsonData = JSON.parse(response);
$.each(jsonData, function(i, bill) {
var newRowContent = "<tr><td>"+bill.billingId+"</td><td>"+bill.billAmount+"</td></tr>";
$("#previousList tbody").append(newRowContent);
});
},
error: function(e) {
alert('Error: ' + e);
}
});
});

populating data to html table using ajax, jquery and making it searchable

I'm loading data dynamically to html table as below. I'm using Datatable for ssearch.
Technology stack used is:
Spring MVC
Hibernate
Ajax
JQuery
function getdata()
{
$.ajax({
type: "GET",
url: "/controllerURL.html", //controller URL
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (results) {
console.log(results)
var success = results.success;
if(success){
var finaldata = "<tbody><thead><tr><th>ID</th><th>data1</th><th>data2</th><th>Update</th></tr></thead>"; //data
var data = results.message;
data = jQuery.parseJSON(data);
alert(data);
for(var i = 0; i < data.length; i++){
var value = data[i];
finaldata = finaldata+ "<tr><th>"+value.ID+"</th><th>"+value.variable1+"</th><th>"+value.variable2+"</th></tr>";
}
finaldata = finaldata + "</tbody>";
$("#tableID").html(finaldata);
}
},
error: function (data) {
alert("fail");
console.log('ajax call error');
}
});
}
I'm now be able to load data into table. but can someone explain how to add search option to it.
You can use datatables click here
It will provide you various inbuilt functionality that you may want to integrate
<!--dependencies for data table -->
<script src="https://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js" type="text/javascript"></script>
Your html should look like this
<table id="stable" class="display table-responsive table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Id</th>
<th>Data1</th>
<th>Data2</th>
<th>Data3</th>
<th>Data4</th>
</tr>
</thead>
finally write this script
$(document).ready(function () {
$('#table').DataTable();
});

Categories

Resources