grab Json object data and inject to html table by looping - javascript

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>

Related

I want to append my api response to datatable

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);
}

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?

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!

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();
});

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