I want to bind dynamic <ul> to a dynamically created <html> table - html

I want to bind dynamic <ul> to a dynamically created <html> table. The first image is correct as per the code.
the image shown below is perfect with the code below,
$("#forbtn").click(function()
{
$.ajax({
url: "json/animals.json",
dataType : "json",
type:"post",
success : function(data) {
//console.log(data);
//const myobj = JSON.parse(data);
//console.log(myobj);
var myobj = data;
var tabdata = myobj.length;
var tablebody = '<table border="1" width="100%"><thead><tr><th class="tabhead"> Name </th><th class="tabhead"> Species </th><th class="tabhead"> Foods </th></tr></thead><tbody>';
for (i=0 ; i < myobj.length; i++)
{
tablebody += '<tr>';
tablebody += '<td class="tabdat">';
tablebody += myobj[i].name;
tablebody += '</td>';
tablebody += '<td class="tabdat">';
tablebody += myobj[i].species;
tablebody += '</td>';
tablebody += '<td class="tabdat">'
tablebody += myobj[i].foods;
tablebody += '</td>';
}
tablebody += '</tbody></table>';
$("#table2").html(tablebody);
$("#table2").css({"margin-top" : "10px"});
$("#table2 .tabhead").css({"padding":"5px" , "background-color" : "#E6E6E6"});
$("#table2 .tabdat").css({"padding":"5px" , "background-color" : "#FAFAFA"});
}
});
});
However, I need something like this, I had tried to include <ul> in the mentioned <td> but it's giving a syntax error of for loop. I don't understand whats wrong in the for loop syntax.
$.ajax({
url: "json/animals.json",
dataType : "json",
type:"post",
success : function(data) {
//console.log(data);
//const myobj = JSON.parse(data);
//console.log(myobj);
var myobj = data;
var tabdata = myobj.length;
var tablebody = '<table border="1" width="100%"><thead><tr><th class="tabhead"> Name </th><th class="tabhead"> Species </th><th class="tabhead"> Foods </th></tr></thead><tbody>';
for (i=0 ; i < myobj.length; i++)
{
tablebody += '<tr>';
tablebody += '<td class="tabdat">';
tablebody += myobj[i].name;
tablebody += '</td>';
tablebody += '<td class="tabdat">';
tablebody += myobj[i].species;
tablebody += '</td>';
tablebody += '<td class="tabdat">'
'<ul><li>' for(j=0 ; j<myobj[i].foods.likes.length; j++)
{
myobj[i].foods.likes[j];
} '<li></ul>';
tablebody += '</td>';
}
tablebody += '</tbody></table>';
$("#table2").html(tablebody);
$("#table2").css({"margin-top" : "10px"});
$("#table2 .tabhead").css({"padding":"5px" , "background-color" : "#E6E6E6"});
$("#table2 .tabdat").css({"padding":"5px" , "background-color" : "#FAFAFA"});
}
});
here is the json
[
{
"name": "Meowsy",
"species" : "cat",
"foods": {
"likes": ["tuna", "catnip"]
}
},
{
"name": "Barky",
"species" : "dog",
"foods": {
"likes": ["bones", "carrots"]
}
},
{
"name": "Purrpaws",
"species" : "cat",
"foods": {
"likes": ["mice" , "milk"]
}
}
]

This code:
tablebody += '<td class="tabdat">'
'<ul><li>' for(j=0 ; j<myobj[i].foods.likes.length; j++)
{
myobj[i].foods.likes[j];
} '<li></ul>';
Needs to be reformatted to:
tablebody += '<td class="tabdat">';
tablebody += '<ul>';
for (j=0; j < myobj[i].foods.likes.length; j++)
{
tablebody += '<li>' + myobj[i].foods.likes[j] + '</li>';
}
tablebody += '</ul>';
There are other ways such as using join, but this shows how to add a for loop inside your string concat.

Related

How to make pagination with pagination js use ajax

I'm trying to create a pagination using pagination js. I use the data using ajax and api. When I try to make it there is an error. How do I fix it?
Am I wrong to make the ajax, but if I don't use pagination js the data is visible in the table. I've tried various ways but I don't really understand using pagination js.
function s() {
var FilterObjDTO = []
console.log(FilterObjDTO);
var SortObjDTO = []
console.log(SortObjDTO);
var PagingObjDTO = { offset: 0, totalPerPage:4, paging: false }
console.log(PagingObjDTO);
var willSendToAPI = {
filter: FilterObjDTO, sort: SortObjDTO, paging: PagingObjDTO
}
console.log(willSendToAPI);
$('#DataTable').pagination({
dataSource: function (done) {
$.ajax({
type: 'GET',
url: origin + '/' + 'id-ID' + '/' + 'DataTable',
data: { input: JSON.stringify(willSendToAPI) },
success: function (data) {
console.log(data);
var html = '';
for (var i = 0; i < data.length; i++) {
html += '<table id="DataTable" style="width: 100%">';
html += '<colgroup>';
html += '<col span="1" style="width: 10%;">';
html += '<col span="1" style="width: 14%;">';
html += '<col span="1" style="width: 29%;">';
html += '<col span="1" style="width: 14%;">';
html += '<col span="1" style="width: 14%;">';
//html += '</colgroup>';
//html += '<tr class="table-border" style="background-color:#f4f5fa;">';
//html += '<th>Title</th>';
//html += '<th class="text-center">Type</th>';
//html += '<th class="text-center">Slug</th>';
//html += '<th class="text-center">PDF</th>';
//html += '<th class="text-center">Edit</th>';
html += '<tbody id="table">';
html += '<tr>';
html += '<td>' + data[i].fTitleID + '</td>';
html += '<td>';
html += '<p class="m-auto t-category">' + data[i].fType + '</p>';
html += '</td>';
html += '<td class="text-center">' + data[i].fSlug + '</td>';
html += '<td class="text-center"><a><i class="fas fa-file-download"></i></a></td>';
html += '<td class="text-center"> <button class="button-edit">edit</button></td>';
html += '</tr>';
html += '</tbody>';
html += '</table>';
}
$('#table').html(html);
}
});
pageSize: 5,
autoHidePrevious: true,
autoHideNext: true,
callback: function(data, pagination) {
// template method of yourself
var html = template(data);
dataContainer.html(html);
}
})
}

Pagination from Ajax response

I'm trying to fetch data from JSON response in a datatable and it works fine. My next step is to add a pagination for all rows. Since I'm using Laravel I've earlier used Laravels built-in system:
{{ $var->links() }}
Now since I'm receiving the response from a POST request to filter out dates, I'm struggling with filtering amount of rows per page. I've tried to Google around without and couln't find a good answer.
I'm a beginner in JavaScript and some support would really help!
This is my code ATM:
$("#date").ready(function() {
$("#date").on('change', function() {
var date = $("#date").find(':selected').val();
var token = $("input[name='_token']").val();
$(document).on('click', '.pagination a', function(event) {
event.preventDefault();
var page = $(this).attr('href').split('page=')[1];
fetch_data(page);
});
$.ajax({
url: "{{ route('mydata') }}",
type: "POST",
data: {
'date': date,
'_token': token
},
dataType: "json",
success: function(data) {
console.log(data);
function status() {
if (data[i].status = 1) {
return '<td class="px-4 py-4"><span class="bg-yellow-500 font-semibold text-white p-2 rounded">Active</span></td>';
}
if (data[i].status = 2) {
return '<td class="px-4 py-4"><span class="bg-blue-500 font-semibold text-white p-2 rounded">Closed</td>';
}
}
function formatDate(date) {
var date = new Date(date);
var yyyy = date.getFullYear().toString();
var mm = (date.getMonth() + 1)
.toString(); // getMonth() is zero-based
var dd = date.getDate().toString();
var h = date.getHours().toString();
var h = ("0" + h).slice(-2);
var m = date.getMinutes().toString();
return yyyy + '-' + (mm[1] ? mm : "0" + mm[0]) + '-' + (dd[1] ? dd :
"0" + dd[0]) + ' ' + h + ':' + m;
}
function remaining_days(start, end) {
var start = new Date(start);
var end = new Date(end);
const _MS_PER_DAY = 1000 * 60 * 60 * 24;
const s = Date.UTC(start.getFullYear(), start.getMonth(), start
.getDate());
const e = Date.UTC(end.getFullYear(), end.getMonth(), end.getDate());
if (end - start < 0) {
return '<span class="text-red-800 font-bold">Late</span>';
} else {
return Math.floor((e - s) / _MS_PER_DAY) + ' Days left';
}
}
var output = '';
for (var i = 0; i < data.length; i++) {
output += '<tr class="bg-gray-100 text-center">';
output += '<td class="px-4 py-4">New</td>';
output += '<td class="px-4 py-4">' + formatDate(data[i].updated_at) +
'</td>';
output += '<td class="px-4 py-4">' + data[i].title + '</td>';
output += '<td class="px-4 py-4">' + data[i].get_admin.first_name +
' ' + data[i]
.get_admin.last_name + '</td>';
output += '<td class="px-4 py-4">#' + data[i].id + '</td>';
output += '<td class="px-4 py-4">' + remaining_days(data[i].created_at,
data[i].end_date) +
'</td>';
output += status();
output += '</tr>';
}
$('#myticketstable').html(output);
},
error: function(xhr) {
if (xhr.status == 422) {
const errors = JSON.parse(xhr.responseText);
console.log(errors);
$.each(xhr.responseJSON.errors, function(i, error) {
console.log('something went wrong');
});
}
}
});
}).trigger('change');});
Best regards

How to make dynamic HTML table data (created using jQuery) clickable?

I am new to these and have tried creating an HTML table dynamically using jQuery. The code is as below. It works fine.
How can I make the table data (value.id) clickable so that it redirects to a different page?
$(document).ready(function() {
var tableData = '';
$.each(xyz, function(key, value) {
tableData += '<tr>';
tableData += '<td>' + value.id + '</td>';
tableData += '<td>' + value.name + '</td>';
tableData += '</tr>';
});
$('#table').append(tableData);
//});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead></thead>
<tbody id="table"></tbody>
</table>
Like this
const xyz = [{
id: 1,
name: "one"
},
{
id: 2,
name: "two"
}
]
$(function() {
const tableData = xyz.map(item => (`<tr><td class="id">${item.id}</td>
<td>${item.name}</td></tr>`));
$('#table').append(tableData.join(""));
$('#table').on("click", ".id", function() {
const id = this.textContent
console.log(id);
// location = "https://google.com/search?q="+id;
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead></thead>
<tbody id="table"></tbody>
</table>
You can enclose your tile content with a "a" tag
`tableData += '<tr>';
tableData += '<td><a href="/you-url/' +value.id+ '">' +
value.id + '<'/a></td>';
tableData += '<td>' +
value.name + '</td>';
tableData += '</tr>';`
I prefer to give the clickable elements a class to reference:
I also have some CSS that sets the cursor to a pointer.
$(document).ready(function () {
var tableData = '';
$.each(xyz, function (key, value) {
tableData += '<tr>';
tableData += '<td class="link">' +
value.id + '</td>';
tableData += '<td>' +
value.name + '</td>';
tableData += '</tr>';
});
$('#table').append(tableData);
//});
});
$(document).on("click","#table .link",function(){
console.log($(this).html());
});
.link{cursor:pointer;}

export data from Firebase into HTML Table

I'm currently developing an app and using firebase as my database and im trying to export data into a table from a firebase because showing the data in the app in table view is harder than i thought so i turned to HTML table and wrote a code but it is not displaying the data that i want. Just to note that im pretty new to all this so any help would be appreciated. Below is my code:
<html>
<body>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 15px;
}
table {
border-spacing: 5px;
}
</style>
<script src="https://www.gstatic.com/firebasejs/5.2.0/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "AIzaSyBuJiZZNabXuBO0ac",
authDomain: "",
databaseURL: "",
projectId: "testproject-5",
storageBucket: "",
messagingSenderId: "2568"
};
firebase.initializeApp(config);
</script>
<head>
<title>Quicksol Attendance</title>
</head>
<table style="width:100%" id="ex-table">
<tr id="tr">
<th>Employee ID</th>
<th>Email</th>
<th>Date </th>
<th>Check in Time</th>
<th>Check out Time</th>
</table>
<script>
var database = firebase.database();
database.ref().once('value', function(snapshot){
if(snapshot.exists()){
var content = '';
snapshot.forEach(function(data){
var val = data.val();
content +='<tr>';
content += '<td>' + val.employeeID + '</td>';
content += '<td>' + val.email + '</td>';
content += '<td>' + val.date + '</td>';
content += '<td>' + val.checkintime + '</td>';
content += '<td>' + val.checkouttime + '</td>';
content += '</tr>';
});
$('#ex-table').append(content);
}
});
</script>
</body>
</html>
I have changed the script inside 'database.ref("/").once('value', function (snapshot) {'
Check the working code jsfiddle
// Initialize Firebase
var config = {
apiKey: "AIzaSyBuJiZZNabXuBU-SoRhZFbdecxs0L2O0ac",
authDomain: "testproject-51bd9.firebaseapp.com",
databaseURL: "https://testproject-51bd9.firebaseio.com",
projectId: "testproject-51bd9",
storageBucket: "testproject-51bd9.appspot.com",
messagingSenderId: "256942259748"
};
firebase.initializeApp(config);
var database = firebase.database();
database.ref("/").once('value', function (snapshot) {
if (snapshot.exists()) {
var content = '';
snapshot.forEach(function (data) {
var val = data.val();
var tableData = [];
var sysDate, checkinTime, checkoutTime, email, employeeId;
for (var checkin in val.Checkin) {
for (var date in val.Checkin[checkin]) {
tableData.push({ 'employeeId': checkin, 'email': val.Checkin[checkin][date]['Email'], 'date': date, 'checkinTime': val.Checkin[checkin][date]['Check in Time'] });
}
}
for (var checkout in val.Checkout) {
for (var checkoutDate in val.Checkout[checkout]) {
var item = tableData.find(function (i) { return i.employeeId == checkout && i.date == checkoutDate; })
if (item)
item.checkoutTime = val.Checkout[checkout][checkoutDate]['Checkout Time'];
}
}
console.log(tableData);
tableData.forEach(function (item) {
content += '<tr>';
content += '<td>' + item.employeeId + '</td>';
content += '<td>' + item.email + '</td>';
content += '<td>' + item.date + '</td>';
content += '<td>' + item.checkinTime + '</td>';
content += '<td>' + (item.checkoutTime ? item.checkoutTime : 'NA') + '</td>';
content += '</tr>';
});
});
$('#ex-table').append(content);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.2.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.2.0/firebase-database.js"></script>
<table style="width:100%" id="ex-table">
<tr id="tr">
<th>Employee ID</th>
<th>Email</th>
<th>Date </th>
<th>Check in Time</th>
<th>Check out Time</th>
</table>

Using JSON response in CFIF

Is it possible to use response.DATA[i][j] in a CFIF statement.
chkUsernameUnique = function(theUsername){
$.ajax({
type: "GET",
url: "/book.cfc",
data: {method: "testFunction", datum: $('#date').val(), returnFormat: "JSON"},
dataType: "json",
success: function(response) {
var str = '<table><tr>';
var i;
var j;
//loop over each column name for headers
for (i = 0; i < response.COLUMNS.length; i++) {
str += '<th>' + response.COLUMNS[i] + '</th>';
}
str += '</tr>';
//loop over each row
for (i = 0; i < response.DATA.length; i++) {
str += '<tr>';
//loop over each column
for (j = 0; j < response.DATA[i].length; j++) {
str += '<td>' + response.DATA[i][j] + '</td>';
}
str += '</tr>';
}
str += '</table>';
$('#debugDiv').html(str);
},
error: function(ErrorMsg) {
console.log('Error');
}
});
}
What I want to do is something like:
<cfif response.DATA[i][j] is 3> str += '<td>test</td>';</cfif>
This returns the following error message: variable [RESPONSE] doesn't exists.
The response variable is the server response for your AJAX request and you are working with it on clientside. Thus you are still in the realm of JavaScript:
if (response.DATA[i][j] == 3) { str += '<td>test</td>'; }
ColdFusion (i.e. <cfif>) is executed on serverside, thus cannot be used to evaluate data during runtime (after the browser requested an URI).