Datatable ajax add row on condition - javascript

So I'm having some trouble setting up datatable using Ajax.
Some context:
I have a Ajax that request certain files information.
The response contains two sets
The files information
The users information (to figure out the user of the files).
I've completed the entire logic without Datatable but now i want to implement it using datatable.
I have 2 condition
Is the end date between today and 4 days from now?
is the end date after 4 days form now?
These condition are used to indicate to the user witch files (project) needs the most attention.
CODE TIME (I'm using the Django framework btw) :D
The AJAX CALL
function ajax_dates() {
$.ajax({
url: "{% url 'get_files_dates' %}",
type: "GET"
}).done(function (object) {
date_calculation(object.dates, object.users);
});
}
THE TWO CONDITION
// CONDITION ONE (ATTEMPT using Datatable)
// Projecten met een waarschuwing
if (enddate.isBetween(today, today.clone().add(4, 'd'))) {
// TABLE ROW VOOR ELK TYPE
running_waring = "";
running_waring += '<tr>';
running_waring += '<td>'+ checker.first_name + " " + checker.last_name+'</td>';
running_waring += '<td>'+ checker.first_name + " " + checker.last_name+'</td>';
running_waring += '<td id="testing">'+result.name+'</td>';
running_waring += '<td>'+result.word_count+'</td>';
running_waring += '<td>'+enddate.format("D MMM YYYY").replace(".","")+'</td>';
running_waring += '<td>'+enddate.format("HH:mm:ss")+'</td>';
running_waring += '<td>Verloopt binnenkort </td>';
running_waring += '<td> Verloopt' + upper_first(today.clone().subtract(0,"d").to(enddate))+'</td>';
running_waring += '</tr>';
$("#lopend_project").html(running_waring);
}
// CONDITION TWO (no datatable)
// Lopende projecten
if (enddate > (today.clone().add(4, 'd'))) {
active_html += "Eigennaar: " + owner.first_name + " " + owner.last_name + "<br>";
if (typeof(checker) === 'undefined') {
active_html += "Checker: None <br>";
} else {
active_html += "Checker: " + checker.first_name + " " + checker.last_name + "<br>";
}
active_html += "Bestand: " + result.name + "<br>" +
"Nog lopend tot: <strong>" + enddate.format("D/M/YYYY HH:mm") + "</strong><br>";
active_html += '<a href=' + "../project/" + result.id + ' >details</a><br><br>';
$("#active_project").html(active_html);
}
});
Condition one seems to work however I'm unable to use filter (it empties the datatable).
I've read on their documentation page that i should use
data and column[] but I dont know how to implement this using my condition.
The full code on this can be found in here :[https://pastebin.com/1qmu9Vva][1]
DATATABLE
$('#project_table').DataTable({
lengthChange: false,
responsive: true,
// scrollY: '50vh',
sScrollY: "100%",
scrollCollapse: true,
paging: false,
stateSave: true,
colReorder: true,
rowGroup: {
startRender: function (rows, group) {
return group + ' (' + rows.count() + ')';
},
dataSrc: 6
},
// taal zorg voor een variabele om de taal in te stellen
"language": {
"lengthMenu": "Toon _MENU_ records per pagina",
"search": "",
"zeroRecords": "Er werd helaas niks gevonden dat voldoet aan uw zoekcriteria",
"emptyTable": "Deze tabel is helaas leeg",
"info": " _TOTAL_ records gevonden",
"infoEmpty": "Niks Gevonden",
"infoFiltered": "(gefilter van _MAX_ record(s))",
"paginate": {
"first": "Eerste",
"last": "Laatste",
"next": "Volgende",
"previous": "Vorige"
}
},
"columnDefs": [
{"width": "10%", "targets": 3}
]
});
I'm Dutch(Belgium) so I apologize in advance for spelling mistakes.
I'll like to thank the awesome folks from stackoverflow in advance.
(seriously you guys are the unseen heroes :D)

Related

Javascript Code not working after pressing on back button on browser

I am working on project which using javascript to get data from database and show it in table.
Every column in the table has action column where user can (edit / delete ..etc)
When the user clicks the edit button he will be redirected to the edit page.
After he has finished the editing, he presses the backbutton on the top left of Chrome browser, to get back to the table page, but the problem is the data is not loading and the table is empty till I refresh the page, then the script code is working and data has been shown in the table.
I don't understand why is that happening, why the javascript code is not working after I click the back button
This is my code it is getting data from database and show it in the table
after calling initTable2 function
var handleISI = function() {
getData();
function getData() {
$.ajax({
async: true,
type: "GET",
url: "/admin/ISIM/GET_ISIMng",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data) {
console.log(data);
data = data;
ISI.initTable2(data);
},
error: function(data) {
console.log(data);
data = [];
ISI.initTable2(data);
},
});
}
};
return {
init: function() {
// initISITable();
handleISI();
handleElements();
// handleAttributes();
handleADDISI();
},
initTable2: function(data) {
//child row delete
ISITable.find("tbody")
.find("tr.shown")
.removeClass("shown")
.next()
.remove();
//dd report check
var isDD = false;
var isDDReport = false;
if (data != undefined) {
ISITable.DataTable().destroy();
ISITable.empty();
ISITable.html("");
if (data != "") {
var thead, tbody;
thead = "<thead><tr>";
console.log(data);
$.each(data[0], function(key, value) {
if (key == "id") {} else {
thead += "<th>" + (jsTranslation[document.documentElement.lang].name) + "</th>";
}
});
(thead += "<th class='text-right'>" + (jsTranslation[document.documentElement.lang].actions) + " </th>"),
(thead += "</tr></thead>");
ISITable.append(thead);
tbody = "<tbody>";
var seq_id = 1;
for (var i = 0; i < data.length; i++) {
if (isDD) {
tbody += "<tr><td class='details-control'></td>";
} else {
tbody += "<tr>";
}
var users_id;
var name_val;
$.each(data[i], function(key, value) {
if (key == "id") {
users_id = value;
} else {
if (key == "name") {
name_val = value;
}
if (key == "username") {
tbody +=
"<td>" +
'<i class="fa fa-user" style="color: #5d56f3;"></i> ' +
value +
"</td>";
} else if (key == "totalSession") {
tbody +=
"<td>" + value.formatNumber() + "</td>";
} else {
console.log(value);
tbody += "<td>" + value + "</td>";
}
}
});
tbody +=
'<td class="text-right"><a href="javascript:;" id="attributebutton" class="btn btn-sm btn-primary btn-sm mt-1 green attribute rounded" data-toggle="tooltip" title=' +
jsTranslation[document.documentElement.lang]
.attribute +
' data-original-title="Attribute" data-id= ' +
users_id +
" data-name= " +
encodeURIComponent(name_val) +
' " ><i class="fa fa-list " style="color:white" ></i></a>';
tbody +=
' <a href="javascript:;" id="editbutton" class="btn btn-sm btn-success btn-sm mt-1 attribute rounded" data-action="Edit" data-toggle="tooltip" title=' +
jsTranslation[document.documentElement.lang].edit +
' data-original-title="Edit" data-id= ' +
users_id +
" data-name= " +
encodeURIComponent(name_val) +
' > <i class="fas fa-pencil-alt " style="color:white" ></i></a>';
tbody +=
' <a href="javascript:;" class="btn btn-sm btn-danger btn-sm mt-1 delete_isi rounded" data-action="Delete" data-toggle="tooltip" title=' +
jsTranslation[document.documentElement.lang]
.delete +
' data-original-title="Delete" data-id= ' +
users_id +
" data-name= " +
encodeURIComponent(name_val) +
' " > <i class="fas fa-trash-alt " style="color:white" ></i></a>';
tbody +=
' <a href="/admin/ISI/' +
users_id +
'" class="btn btn-sm btn-sm mt-1 btn-warning green rounded" data-action="Delete" data-toggle="tooltip" title=' +
jsTranslation[document.documentElement.lang]
.manage +
' data-original-title="Manage" data-id= ' +
users_id +
" data-name= " +
encodeURIComponent(name_val) +
' " > <i class="fa fa-globe " style="color:white" ></i></a> ';
tbody += "</td>";
tbody += "</tr>";
seq_id++;
}
tbody += "</tbody>";
tbody += " ";
ISITable.append(tbody);
}
}
$(document).ready(function() {
$('[data-toggle="tooltip"]').tooltip();
});
var table = ISITable;
// var columnDefs = [{ className: "text-left", targets: "_all" }];
if (data == undefined) {
// columnDefs = [{ className: "dt-center", targets: "_all" }];
}
var oTable = table.DataTable({
destroy: true,
ordering: false,
paging: true,
lengthMenu: [
[5, 10, 15, 20, -1],
[5, 10, 15, 20, "All"], // change per page values here
],
pageLength: 10,
dom: "<'row' <'col-md-12'T>><'row'<'col-md-9 col-sm-12 topLenght'l><'col-md-3 col-sm-12'f>r><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>",
// columnDefs: columnDefs,
language: $.fn.dataTable.language,
className: "dt-center",
language: {
url: window.location.origin + "/i18N/" + document.documentElement.lang + ".json",
},
});
//Top lenght selector
var x = 10;
if (x == "") {
x = "10";
}
var optionhtml = "";
if (x == "10") {
optionhtml += "<option selected value='10'>10</option>";
} else {
optionhtml += "<option value='10'>10</option>";
}
if (x == "20") {
optionhtml += "<option selected value='20'>20</option>";
} else {
optionhtml += "<option value='20'>20</option>";
}
if (x == "30") {
optionhtml += "<option selected value='30'>30</option>";
} else {
optionhtml += "<option value='30'>30</option>";
}
var xx = " ";
//top kutusunu taşır.
$("#reporttable_wrapper").find(".topLenght").append(xx);
},
};
})();
jQuery(document).ready(function() {
ISI.init(); // init metronic core componets
});
I see that this is a metronic table. I have worked on a metronic website, are you using the regular JS version? I can't tell which one you are using.
I have used the Angular version and have had this problem occur when there was an asynchronous process inside a synchronous function.
From looking at the code, I can't see what the functions, handleISI(), handleElements(), handleADDISI() do so I cannot comment on them. I tried searching a few snippets on the latest metronic version, and couldn't find them. If you are using a pre v7 version, please let me know.
After all that, looking at the code you have given me, there are only two things that stand out to me
The init function is synchronous and your ajax call is async. Meaning that your handlers get initiated before the data is retrieved. Which may or may not be the cause of your problem. You haven't shared the edit action either, I will have to assume that the edit action might not be adding the data locally and only on the server, which means that your table might be getting initialized before the new data call comes since the variable data is shared. Remember, even the put request takes a little bit of time.
Turning the process async using promises might fix your problem.
You are using the back button on chrome. If you don't force update on refresh, then there is a high chance that a cached version is being served to you and refreshing makes chrome fetch again.
You will have to share more code with us to get a more accurate answer. If I have completely missed the edit action being handled in the given code, please let me know where.

datatable ajax xml display with master-detail relationship

Through that jQ bootstrap 4 datatable grid (datatable.net) I want for tabular display the following xml file:
<?xml version="1.0" encoding="UTF-8"?>
<persns>
<prsn>
<fname>Smith</fname> <!-- first name-->
<lname>Milton</lname> <!-- last name -->
<age>44</age>
<e-mail>smilt#gmail.com</e-mail>
<phnmbr>3568236712</phnmbr>
<addrss>5th summer st, mntb</addrss>
<city>Portland</city>
</prsn>
<prsn>
<fname>Ken</fname>
<lname>Jackson</lname>
<age>37</age>
<e-mail>ken.jackson#yahoo.com</e-mail>
<phnmbr>2638762076</phnmbr>
<addrss>19th Penfield ave, brtcl</addrss>
<city>Kelowna</city>
</prsn>
<prsn>
<fname>Susan</fname>
<lname>Arkland</lname>
<age>48</age>
<e-mail>s.arklnd#hotmail.com</e-mail>
<phnmbr>50834219704</phnmbr>
<addrss>34th Mansfield st, sgtp</addrss>
<city>Raleigh</city>
</prsn>
<prsn>
<fname>Patsy</fname>
<lname>Brighton</lname>
<age>38</age>
<e-mail>patsy.brghton#gmail.com</e-mail>
<phnmbr>814522096358</phnmbr>
<addrss>12th Peel st, pnslv</addrss>
<city>Philadelphia</city>
</prsn>
<prsn>
<fname>John</fname>
<lname>Torg</lname>
<age>54</age>
<e-mail>john.torg#tzeus.com</e-mail>
<phnmbr>042197327784</phnmbr>
<addrss>27th north st, cnda</addrss>
<city>Penticton</city>
</prsn>
but with master-detail functionality as it is shown over the following fiddle link:
https://jsfiddle.net/nnb97rh9/3/
Only that up to that fiddle there is .json data ! (and I need for .xml display)
The corresponding (almost functional) .js (through the master table I only want to display the following table headers:
fname, lname, age, city while the rest would be hidden; they'll only be displayed as related child table lines) is as follows:
$(function(){
var prstbl = $("#prsns").dataTable(columns: [{"class":'details-control',
"orderable":false, "data":null, "defaultContent":''},
{dtaTbl:"fname"},
{dtaTbl:"lname"},
{dtaTbl:"age"},
{dtaTbl:"city"},
{dtaTbl:"e-mail", "visible":false},
{dtaTbl:"phnmbr", "visible":false},
{dtaTbl:"addrss", "visible":false}
]}),
oTable = $('#prsne').DataTable()
function format(d)
{
return '<table cellpadding="3" cellspacing="0" border="0" style="padding-
left:40px">'
+ '<tr>' + '<td>e-mail addrss</td>'
+ '<td>' + d.email + '</td>' + '</tr>'
+ '<tr>' + '<td>phn nmber</td>'
+ '<td>' + d.phnmbr + '</td>' + '</tr>'
+ '<tr>' + '<td>address</td>'
+ '<td>' + d.addrss + '</td>' + '</tr>'
+ '</table>'
}
$.ajax({type:"GET", url:"persns.xml", dataType:"xml", success:
function(xml)
{
var prsns = $(xml).find("prsn")
prsns.each(function(idx, prs)
{
var prs = $(prs), dtaTbl = []
prs.children().each(function(j,chdnd)
{
dtaTbl.push($(chdnd).text())
})
prstbl.fnAddData(dtaTbl)
})
}
})
$('#prsns tbody').on('click', 'td.details-control', function()
{
var tr = $(this).closest('tr'),
row = oTable.row(tr)
if(row.child.isShown()) // if the row is already expanded,
collapse it
{
row.child.hide()
tr.removeClass('shown')
}
else // if collapsed row, expandit it
{
row.child(format(row.data())).show()
tr.addClass('shown')
}
})
})
The relevant .html part is like this:
<body>
<h5>Master-detail persons display</h5>
<table id="prsns" border="1" class="table display" width="60%">
<thead><tr><th></th><th>frst nme</th><th>name</th><th>age</th>
<th>city</th> <th>e-mail addrss</th></tr></thead>
<tbody></tbody>
</table>
</body>
And there is also a small .css file like this:
td.details-control
{
background:url('https://raw.githubusercontent.com/DataTables/DataTables/1.10.7/examples/resources/details_open.png') no-repeat center center;
cursor: pointer;
}
tr.shown td.details-control
{ background:url('https://raw.githubusercontent.com/DataTables/DataTables/1.10.7/examples/resources/details_close.png') no-repeat center center;
}
I repeat, all the displaying I need to be done regarding this .xml file and not .json or only .html !
I know how to do it with .json table.
So you guys please help me with this issue.
Thank you all in advance
There are multiple issues with the code, too much to describe. Below is the corrected code.
Please note I am using jsFiddle mechanism to retrieve XML file, replace with your own.
(function () {
function format(d) {
return '<table cellpadding="3" cellspacing="0" border="0" style="padding-left: 40 px ">' +
'<tr>' + '<td>e-mail addrss</td>' +
'<td>' + d['e-mail'] + '</td>' + '</tr>' +
'<tr>' + '<td>phn nmber</td>' +
'<td>' + d['phnmbr'] + '</td>' + '</tr>' +
'<tr>' + '<td>address</td>' +
'<td>' + d['addrss'] + '</td>' + '</tr>' +
'</table>';
}
var prstbl = $("#prsns").DataTable({
columns: [
{
"class": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{
data: "fname"
},
{
data: "lname"
},
{
data: "age"
},
{
data: "city"
},
{
data: "e-mail",
"visible": false
},
{
data: "phnmbr",
"visible": false
},
{
data: "addrss",
"visible": false
}
]
});
$.ajax({
type: "POST",
url: "/echo/xml",
data: {
xml: '<?xml version="1.0" encoding="UTF-8" ?><persns>'
+ '<prsn><fname>Smith</fname><lname>Milton</lname><age>44</age><e-mail>smilt#gmail.com</e-mail><phnmbr>3568236712</phnmbr><addrss>5th summer st, mntb</addrss><city>Portland</city></prsn>'
+ '<prsn><fname>Ken</fname><lname>Jackson</lname><age>37</age><e-mail>ken.jackson#yahoo.com</e-mail><phnmbr>2638762076</phnmbr><addrss>19th Penfield ave, brtcl</addrss><city>Kelowna</city></prsn>'
+ '<prsn><fname>Susan</fname><lname>Arkland</lname><age>48</age><e-mail>s.arklnd#hotmail.com</e-mail><phnmbr>50834219704</phnmbr><addrss>34th Mansfield st, sgtp</addrss><city>Raleigh</city></prsn>'
+ '<prsn><fname>Patsy</fname><lname>Brighton</lname><age>38</age><e-mail>patsy.brghton#gmail.com</e-mail><phnmbr>814522096358</phnmbr><addrss>12th Peel st, pnslv</addrss><city>Philadelphia</city></prsn>'
+ '<prsn><fname>John</fname><lname>Torg</lname><age>54</age><e-mail>john.torg#tzeus.com</e-mail><phnmbr>042197327784</phnmbr><addrss>27th north st, cnda</addrss><city>Penticton</city></prsn>'
+ '</persns>',
},
dataType: 'xml',
success: function (xml) {
var prsns = $(xml).find("prsn");
prsns.each(function (idx, prs) {
var rowData = [];
$(prs).children().each(function (j, chdnd) {
rowData[$(chdnd).get(0).tagName] = $(chdnd).text();
});
prstbl.row.add(rowData);
});
prstbl.draw();
}
});
$('#prsns tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = prstbl.row(tr);
// if the row is already expanded, collapse it
if (row.child.isShown()) {
row.child.hide();
tr.removeClass('shown');
// if collapsed row, expand it
} else {
row.child(format(row.data())).show();
tr.addClass('shown');
}
});
})();
See updated example for code and demonstration.

Why my dataTables does not appear using $.each inside function?

I have nested array json object (Layer 1, Layer 2 and Layer 3). My problem is dataTables does not appear. Any related CDN has been imported. The table just only display <thead> section. I have referred many websites, but it did not solve my problem.
Earlier I was using standard table to display the values inside Layer 3 json using <tbody>, <tr> and <td>, do the result is successful. But now I removed all that and try to use dataTable as I need its' features.
I successfully displayed value id for Layer 1 and Layer 2. But for my case below, it is unsuccessfully to display Layer 3 information (l3_id, l3_name, etc..) in dataTables.
JSON
{
"status": "Success",
"data": [{
"project_id": "1",
"project_name": "project name",
"l1_task": [{
"l1_id": "1",
"l1_name": "Layer 1",
"l2_task": [{
"l2_id": "1",
"l2_name": "Layer 2",
"l3_task": [{
"l3_id": "1",
"l3_name": "Layer 3.1"
},
{
"l3_id": "2",
"l3_name": "Layer 3.2"
}
]
}]
}]
}]
}
JS
$(document).ready(function() {
loadtable();
$('#Layer3Table').DataTable({
ajax: {
url: "exampleData/activity.json"
},
columns: [{
data: "l1_task.0.l2_task.0.l3_task.0.l3_id"
},
{
data: "l1_task.0.l2_task.0.l3_task.0.l3_name"
}
],
});
function loadtable() {
var project = '';
$.ajax({
url: url_project_detail,
crossDomain: true,
type: 'POST',
dataType: 'json',
data: "data",
success: function(response) {
if (response.status == "Success") {
// Layer 1 array object
$.each(response.data[0].l1_task, function(key, value) {
project +=
"<div>" +
"<div>";
// Layer 2 array object
$.each(value.l2_task, function(key, value) {
project +=
"<div>" +
"<div>" +
// Layer 3 array object
"<div class='table-responsive'>" +
"<table id='Layer3Table' class='table table-striped' style='width:100%'>" +
"<thead>" +
"<tr>" +
"<th class='text-center'>ID</th>" +
"<th class='text-center'>Activity Name</th>" +
"</tr>" +
"</thead>" +
"</table>" +
"</div>";
}); // for Layer 2
project += "</div>" + "</div>";
}); // for Layer 1
$("#projectDetail2").append(project);
} else {}
},
error: function(e) {}
});
}
});
I just got the solution by removing this dataTables.
$('#Layer3Table').DataTable({
ajax: {
url: "exampleData/activity.json"
},
columns: [{
data: "l1_task.0.l2_task.0.l3_task.0.l3_id"
},
{
data: "l1_task.0.l2_task.0.l3_task.0.l3_name"
}
],
});
and initiate dataTables at this section
}); // for Layer 1
$("#projectDetail2").append(project);
$('#Layer3Table').DataTable();
} else {}
UPDATE
Nice job on figuring this one out on your own, OP. I will include the solution in my answer as well.
You were appending the table after calling datatables so it makes sense you would need to put the call to datatables after appending the table with the data in it. I should have caught that, nice job!
Your success function does not loop through l3_task. Try this ..
success: function(response) {
if (response.status == "Success") {
// Layer 1 array object
$.each(response.data[0].l1_task, function(key, value) {
project +=
"<div>" +
"<div>";
// Layer 2 array object
$.each(value.l2_task, function(key1, value1) {
project +=
"<div>" +
"<div>" +
// Layer 3 array object
"<div class='table-responsive'>" +
"<table id='Layer3Table' class='table table-striped' style='width:100%'>" +
"<thead>" +
"<tr>" +
"<th class='text-center'>ID</th>" +
"<th class='text-center'>Activity Name</th>" +
"</tr>" +
"</thead>";
$.each(value1.l3_task, function(k, v) {
project +=
"<tr>" +
"<td>" + v.l3_id + "</td>" +
"<td>" + v.l3_name + "</td>" +
"</tr>";
});
project +=
"</table>" +
"</div>";
}); // for Layer 2
project += "</div></div></div></div>";
}); // for Layer 1
$("#projectDetail2").append(project);
$('#Layer3Table').DataTable();
} else {}
},

Pass JSON result from AJAX to HTML

I am querying a fuseki server using AJAX and the result that I am getting is a JSON object.
I would like to use pagination to go through the result with a limit of records per page. I have tried to send the JSON object to a div in the html file but it is not working. Is there a workaround this? Here is my code:
function myCallBack2(data) {
var all_results = '';
for (var i = 0; i < data.results.bindings.length; i++) {
var bc = '';
if (i % 2 == 0) {
bc = '#b8cddb';
} else {
bc = '#f2f5f7';
}
all_results += '<div class="all_results" style="background-color:' + bc + '">';
for (var j = 0; j < data.head.vars.length; j++) {
var text = data.results.bindings[i][data.head.vars[j]].value;
var type = data.results.bindings[i][data.head.vars[j]].type;
all_results += '<div class="result_row">';
if (type == ('literal')) {
all_results += '<p> ' + data.head.vars[j] + ": " + text + '</p>';
} else {
all_results += '<a href=' + text + " title=" + data.head.vars[j] + '>' + text + '</a>';
}
all_results += '</div>';
}
all_results += '</div>';
}
$('#result').html(all_results);
}
function doSparql() {
var myEndPoint = "http://localhost:3030/Test/query";
name = document.getElementById("search").value;
var requiredName = "?Author foaf:firstName \"" + name + "\".}";
myQuery = ["PREFIX dcterms: <http://purl.org/dc/terms/>",
"PREFIX foaf: <http://xmlns.com/foaf/0.1/>",
"PREFIX locah: <http://data.archiveshub.ac.uk/def/>",
"SELECT ?Register ?Id ?Date ?Type",
"WHERE{",
"?Register dcterms:creator ?Author.",
"?Register dcterms:identifier ?Id.",
"?Register dcterms:type ?Type.",
"?Register locah:dateCreatedAccumulatedString ?Date.",
requiredName
].join(" ");
console.log('myQuery: ' + myQuery);
window.alert(myQuery);
$.ajax({
dataType: "jsonp",
url: myEndPoint,
data: {
"query": myQuery,
"output": "json"
},
success: myCallBack2,
error: myError
});
console.log('After .ajax');
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//raw.github.com/botmonster/jquery-bootpag/master/lib/jquery.bootpag.min.js"></script>
<div id="page-selection1" "></div>
<div id="result " class="result "></div>
<div id="page-selection2 "></div>
<script>
$('#page-selection1,#page-selection2').bootpag({
total: 50,
page: 1,
maxVisible: 5,
leaps: true,
firstLastUse: true,
first: 'First',
last: 'Last',
wrapClass: 'pagination',
activeClass: 'active',
disabledClass: 'disabled',
nextClass: 'next',
prevClass: 'prev',
lastClass: 'last',
firstClass: 'first'
}).on("page ", function(event, num) {
$("#result ").html("Page " + num);
});
</script>
I am expecting to show part of the results instead Page 1, Page 2... in #result according to a limit per page.

How to create tables in jQuery for $.each()

I am a beginner programmer that is trying to display data results I get from Etsy API into a table as shown below:
<tr><td>item.images</td><td><tr>item.title</tr><tr>item.price</tr></tr>
However, I am unable to display the results in a table and am having problems applying the solutions to my situation
Here is the set of working codes, and I have commented out my failed attempts.
<script type="text/javascript">
(function($){
$(document).ready(function(){
$('#etsy-search').bind('submit', function() {
api_key = "XXXXXXXXXXXXXXXXXXXXX";
terms = $('#etsy-terms').val();
etsyURL = "https://openapi.etsy.com/v2/listings/active.js?keywords="+
terms+"&limit=3&includes=Images:1&api_key="+api_key;
$('#etsy-images').empty();
$('<p></p>').text('Searching for '+terms).appendTo('#etsy-images');
$.ajax({
url: etsyURL,
dataType: 'jsonp',
success: function(data) {
if (data.ok) {
// Commented out are my failed attempt
//var table = "<table>";
$('#etsy-images').empty();
if (data.count > 0) {
$.each(data.results, function(i,item) {
$("<img/>").attr("src", item.Images[0].url_75x75).appendTo("#etsy-images").wrap(
"<a href='" + item.url + "'></a>"
//table+='<tr><td>'+item.title+'</td><td>'+item.price+'</td></tr>';
//}
);
// table+='</table>';
// $("#etsy-images").html( table );
if (i%4 == 3) {
$('<br/>').appendTo('#etsy-images');
}
});
} else {
$('<p>No results.</p>').appendTo('#etsy-images');
}
} else {
$('#etsy-images').empty();
alert(data.error);
}
}
});
return false;
})
});
})(jQuery);
</script>
<body>
<form id="etsy-search">
<input id="etsy-terms" size="32">
<button>Search!</button>
</form>
<div id="etsy-images"></div>
</body>
Additional info:
1. Currently the results looks like this:
After a successful search, the JSON results looks like this:
[
{
"listing_id": 123,
"state": "active",
"user_id": 123,
"category_id": 123,
"title": "XXX",
"price": "2.99",
"currency_code": "USD"
....
}
]
I eventually used trHTML to format the table:
var trHTML = '';
$('#etsy-table').empty();
$.each(data.results, function(i,item) {
trHTML += '<tr><td>' + '<a href="'
+ item.url +'" target="_blank" style="color: white"><img src="'
+ item.Images[0].url_75x75 + '" border="0"></a></td><td><tr>'
+ item.title + '</tr><tr>'
+ item.price + '</tr><tr><a href="'
+ vimg +'" target="_blank" style="color: white"><img class="autosizeImage"src="'
+ vimg + '" border="0"></a></tr></td></tr>';
})
$('#etsy-table').append(trHTML);
Firts step check the "crossdomain" someones browsers don't allow get data between different domains, you can enabled it with headers to allow than.

Categories

Resources