I want to append my api response to datatable - javascript

I have a response in json which I am getting from the api. I want to embed that into the datatable. One by one so they can be shown in a row. But i am getting an error and the all of the data in being appended under one column.
This is my json response
And I am trying to read the data through the fetch API and then appending it to the table.
<table id="table1" class="display" style="min-width: 845px">
<thead>
<tr>
<th>ID</th>
<th>File Name</th>
<th>Action</th>
</tr>
</thead>
<tbody id="tbodydata">
</tbody>
</table>
fetch api call is below
fetch('https://e728-185-202-239-227.ngrok.io/pakgentext/getFilesByPath/?path='+product , {
method: "GET",
headers : {
'Content-Type' : 'application/json'
},
})
.then((response) => response.json())
.then((resp) => {
console.log(resp);
if(resp.message == "Success"){
$.each(resp.doc, function (index, value) {
$("#table1 ").append('<td>'+value+'</td>');
});
}else{
}
})
I tried looping through my response to append it one by one but its all appending in the same column.

You need to take action on resp.doc.txtFiles, not resp.doc. Look through the array and construct a table row from each item. For better performance it is better to first generate the HTML of all rows, then update the DOM, e.g. reduce the number of .append() to one.
From your example it is not clear what the table columns ID, File Name, and Action entail, so I took a guess.
Here is the code to generate the HTML from the response, and update the DOM:
if(resp.message == "Success") {
let html = resp.doc.txtFiles.map(fileName => {
let id = fileName.replace(/\.txt$/, '');
let action = '??';
return '<tr> <td>'+id+'</td> <td>'+fileName+'</td> <td>'+action+'</td> </tr>';
}).join(' ');
$("#table1 tbody").append(html);
}
UPDATE 1 The OP changed the format of the JSON response to:
{
"message": "Success",
"doc": [
{ "filename": "PhD-D-E_T-F-001.txt" },
{ "filename": "PhD-D-E_T-F-002.txt" },
{ "filename": "PhD-D-E_T-F-003.txt" }
]
}
With this, the code changes to this:
if(resp.message == "Success") {
let html = resp.doc.map(obj => {
let fileName = obj.filename;
let id = fileName.replace(/\.txt$/, '');
let action = '??';
return '<tr> <td>'+id+'</td> <td>'+fileName+'</td> <td>'+action+'</td> </tr>';
}).join(' ');
$("#table1 tbody").append(html);
}

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

Refreshing a table without reloading a page in spring mvc using javascript

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!

grab Json object data and inject to html table by looping

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>

jquery each function on string variable

I have wrote a function in javascript which takes title attributes of <tr> calls ajax then after some operation it retreive some title attributes from them. depending on that title attribute i want to remove those <tr> rows
function currentTicketStatus() {
var ids = '';
$('tbody tr[title]').each(function() {
ids += ((ids == '') ? '' : ',') + $(this).attr('title');
});
$.ajax({
url: 'ajaxExecute.aspx?Fn=CTS',
type: 'POST',
context: document.body,
cache: false,
data: 'Tickets=' + ids,
success: function(response) {
if (response != '') {
if (response.substr(0, 5) != 'ERROR') {
var sTickets = response.split('|');
sTickets.each(function() {
$(this).parent().parent().remove();
});
}
}
}
});
}
Example : at the time of ajax call ids="100,101,102,103,104" after ajax call sTickets="101|102" . Now remove those rows with attributes of sTickets
HTML (Not Exactly )
<tbody>
<tr title="100"> some data part </tr>
<tr title="101"> some data part </tr>
<tr title="102"> some data part </tr>
<tr title="103"> some data part </tr>
</tbody>
the this in the each is a "title" (a string), you need the DOM element (the <tr>) instead
sTickets.each(function() {
$('tbody tr[title="'+ this +'"]').remove();
});
demo
try this code in your success function :
success: function(response) {
if (response != '') {
if (response.substr(0, 5) != 'ERROR') {
var sTickets = response.split('|');
$.each(function(i,v){ $('tr[title=' + v + ']') }).remove();
}
}
Explanation:
1- SELECT DOM element by attribute :
$('[ATTRIBUTE=VALUE]') // $('[title="myTitle"]')
you can find more in this link http://api.jquery.com/attribute-equals-selector/
2 - $.each Iteration
which can be used to seamlessly iterate over both objects and arrays.
more : http://api.jquery.com/jquery.each/

Categories

Resources