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?
Related
I am having a simple table which shows basic details about cusotmers. Each customer belongs to one of available customer groups. I also have a dropdown on the top of it where I can toggle between available customer groups and want to update the table with customers belonging to that particular group. Right now everything happens using page reload which is quite inefficient I know. Is there a way to use js here and make only the table section refresh without reloading the entire page.
#GetMapping(WebControllerConstants.RIDER_MAPPING)
public ModelAndView riderMapping(#RequestParam(value = "groupId", required = false) String groupId) {
String group = "1";
if (groupId != null) {
group = groupId;
}
ModelAndView model = new ModelAndView("riderGroupDetails");
model.addObject("list", riderService.findRiderByGroupId(group));
model.addObject("riderGroupList", riderGroupService.findAllGroups());
return model;
}
<select id="category" name="category" onchange="GetAllDetails(this.value);">
//some options here
</select>
<table class="table table-striped table-bordered zero-configuration dataTable">
<thead>
<tr>
<th>ID</th>
<th>FirstName</th>
<th>LastName</th>
<th>Mobile No</th>
</thead>
<tbody>
<c:set var="id" value="${1}" />
<c:forEach var="rider" items="${list}">
<tr>
<td>
<c:out value="${id}" />
</td>
<td>
<c:out value="${rider.firstname}" />
</td>
<td>
<c:out value="${rider.lastname}" />
</td>
<td>
<c:out value="${rider.mobile}" />
</td>
</tr>
<c:set var="id" value="${id + 1}" />
</c:forEach>
</tbody>
</table>
<script>
$(window).on(
'load',
function() {
$.urlParam = function(name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)')
.exec(window.location.search);
return (results !== null) ? results[1] || 0 : false;
}
if ($.urlParam('groupId') == false) {
} else {
var groupId = $.urlParam('groupId');
console.log('groupId ' + groupId);
$("#category").val(groupId);
}
});
function GetAllDetails(value) {
groupvalue = value;
console.log(groupvalue);
var url = "${context}/rider/mapping?groupId=" + value;
//AJAX works here to send a request but table doesn't refresh.
window.location = url;
}
</script>
//AJAX works here to send a request but table doesn't refresh.
Here your AJAX could listen to a response code. If the code says transaction happened correctly you could create a js function that updates the page info while not refreshing it. The new info can be handled from js from the begining or on the response you can pass the info to be updated and pass it to the redrawing function.
Example:
function updateDBService(request){
var dataStr = JSON.stringify(request);
var url = '/updateDBService';
$.ajax({
url: url,
contentType: "application/json",
data: dataStr,
type: "POST",
statusCode: {
403: function () {
},
404: function () {
},
500: function (data) {
}
},
//This is your response object (data), which you can use to update the onscreen info
success: function (data) {
redrawInfo();
},complete: function(data) {
}
});
}
For this I usually create a controller different from the views controller so I can handle response classes, request classes and all sorts of stuff. Here a controller that uses POST method would be required.
Hopefully this helps you!
I have to grab "data" items and loop and inject to specific table like bellow. How is that possible from javascript/jquery? I have attached picture of my Json response of ajax call check to get idea about Json i need to be processed. Any question welcome. Thanks in advance....
Table:
<table>
<tr>
<th>Ebay Image</th>
<th>Item Title</th>
</tr>
<tr need to loop this tr as per json objects>
<td><img src="link defined from json value"></td>
<td>title from json value</td>
</tr>
</table>
Jquery Ajax call:
$.post("/CategoryResearch/Search", { OperationName: _operationname, calltype: _calltype, page: _page, keywords: _keywords, type: _type, location: _location })
.done(function (data) {
if (data != null) {
$("#normalState").fadeOut();
//Loop and inject html table data to specific table
console.log(data);
}
});
Json Picture from console.log(data) -
Table:
(dont forget to add tableId as id and remove de tr tag of sample data)
<table id="tableId">
<tr>
<th>Ebay Image</th>
<th>Item Title</th>
</tr>
</table>
Jquery Ajax call:
(on edit i'm placing the entire loop directly in ajax call for simplify to you)
$.post("/CategoryResearch/Search", { OperationName: _operationname, calltype: _calltype, page: _page, keywords: _keywords, type: _type, location: _location })
.done(function (data) {
if (data != null) {
$("#normalState").fadeOut();
//Loop and inject html table data to specific table
if ($("#tableId tbody").length === 0) {
$("#tableId").append("<tbody></tbody>");
}
var jsonDataObject = JSON.parse(data);
$.each(jsonDataObject, function(i, item){
$("#tableId tbody").append(
"<tr>" +
"<td><img src=\"" + item.EbayImageUrl + "\"></td>"
"<td>" + item.EbayTitle + "</td>" +
"</tr>"
);
});
console.log(data);
}
});
You can loop through the array that you get as a response with a for...
$.ajax({
type: 'POST',
url: '/CategoryResearch/Search',
data: { OperationName: _operationname, calltype: _calltype, page: _page, keywords: _keywords, type: _type, location: _location },
dataType: 'json',
success: function(data) {
if (data != null) {
$("#normalState").fadeOut();
var rows = [];
for (var i=0, l=data.length; i<l; i++)
rows.push('<tr><td>'+data[i].EbayImageUrl+'</td><td>'+data[i].EbayTitle+'</td></tr>');
$('table tbody').html(rows.join(''));
}
}
});
have you tried using append?
<table id="appendedTable">
<tr>
<th>
header 1
</th>
</tr>
</table>
<script>
$(document).ready(function(){
$('#appendedTable').append('<tr><td>concatenate here your json value</td></tr>');
});
</script>
Parse the response
(I think I'm wrong about this part. I haven't used jQuery in years. I think it parses it for you, but, just in case...)
The response from the server is a string. Parse it with JSON.parse.
let myData = JSON.parse(data);
Based on the supplied screenshot, it looks like you get an array of objects.
Iterate the array
Loop over each element of the array with Array.forEach.
Add Rows to your table
Get a reference to your table with document.getElementsByTagName or document.getElementById, et al.
Add rows and cells with HTMLTableElement.insertRow() and HTMLTableRowElement.insertCell().
Example
const myData = [{
EbayImageUrl: 'http://via.placeholder.com/100x50/ff0000/ffffff',
EbayTitle: 'example title'
}, {
EbayImageUrl: 'http://via.placeholder.com/100x50/00ff00/ffffff',
EbayTitle: 'example title'
}, {
EbayImageUrl: 'http://via.placeholder.com/100x50/0000ff/ffffff',
EbayTitle: 'example title'
}];
const table = document.getElementsByTagName('table')[0];
myData.forEach(item => {
let row = table.insertRow();
row.insertCell().innerHTML = `<img src="${item.EbayImageUrl}">`;
row.insertCell().innerHTML = item.EbayTitle;
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" rel="stylesheet" />
<table>
<tr>
<th>Ebay Image</th>
<th>Item Title</th>
</tr>
</table>
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>
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();
});
I am developing a mobile app using Phonegap and jQuery Mobile. Basically for the first time when the app loads the data which gets populated using AJAX comes fine but It doesn't update.
Example: If there are 5 rows of data coming from the database and with some users action 1 more row has been added in the database but it still displays 5 rows. Currently it updates only if I exit app fully.
Also to solve this problem I have tried the following:
tbody.append(tableCells).load();
tbody.append(tableCells).trigger('create');
tbody.append(tableCells).trigger('refresh');
Any solution/idea how can I update it live or something without a user exits the app completely? Please see the below code.
Code:
HTML:
<table id="myPendingChallenges-table" width="100%">
<thead>
<tr>
<th>Game Type</th>
<th>Team Name</th>
<th>Initiator Name</th>
</tr>
</thead>
<tbody></tbody>
</table>
to append rows inside the
JS: tbody.append(tableCells);
AJAX:
var currentUser = window.localStorage.getItem("currentUser");
user = JSON.parse(currentUser);
var username = user.username; //User name
//alert (username+', '+t_name+', '+formAction);
$.ajax({
type: 'POST',
url: 'http://www.example.com/webservice/index.php',
data: {username: username},
dataType : 'json',
success: function(data){
var json = JSON.stringify(data);
window.localStorage.setItem("teamChallenges", json);
challengePopulate();
},
error: function(){
alert('error!');
}
});
return false;
function challengePopulate()
{
var json = window.localStorage.getItem("teamChallenges");
var data = null;
if(!json)
data = JSON.stringify(window.teamChallenges);
var data = JSON.parse(json);
if(!data)
return;
var fields = ["game_type", "t_name", "ini_name"];
populatePCTable("#myPendingChallenges-table", fields, data);
}//end challengePopulate
function populatePCDTable(tableId, fields, data)
{
var tbody = $(tableId + " tbody");
var row = null;
for(var i in data) {
row = data[i];
if(!row)
continue;
var tableCells = "";
var fieldName = "";
for(var j in fields){
fieldName = fields[j];
teamName = row[fields[1]];
gameParam = row[fields[3]];
if(row[fieldName] == 'weighin'){
game_type = 'weighin';
row[fieldName] = '<img src="images/weightGame.png" width="100%" />';
}else if (row[fieldName] == 'activity'){
game_type = 'activity';
row[fieldName] = '<img src="images/activityGame.png" width="100%" />';
}
tableCells += "<td onClick=\"setPendingChallTitle('"+teamName+"');pendingchallengeDetails('"+teamName+"');\"><a href='#pendingChallengesDetailsPage'>"+row[fieldName]+"</a></td>";
}
tbody.append("<tr>" + tableCells + "<td onClick=\"ignorePendingChallenge(this,'"+teamName+"');\"><a href=''><img src='images/close_button.png' title='Ignore Challenge' /></a></td></tr>");
}
}//end function populatePCDTable