How to make pagination with pagination js use ajax - html

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

Related

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

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

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.

Populate HTML table with JSON data

We would be grateful for some guidance, [we are early into coding] and have looked at lots of examples but can cannot get our JSON to import into the table.
At that moment we have the table data in-line however a correctly formatted JSON file is now available and automatically updates and we want to load it into the table on the fly when the page is loaded.
This is an example of what were currently use:
<div>
<p> *** OTHER STUFF HERE ***<p/>
<table id="gable">
<colgroup>
<col class="twenty" />
<col class="fourty" />
<col class="thirtyfive" />
<col class="twentyfive" />
</colgroup>
<tr>
<th onclick="sortTable(0)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspCOUNTRY</th>
<th onclick="sortTable(1)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspLOCATION</th>
<th onclick="sortTable(2)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspBALANCE</th>
<th onclick="sortTable(3)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspDATE</th>
</tr>
</table>
</div>
<script>
var data = [
{ "COUNTRY":"UK", "LoC":"London", "BALANCE":"78,573", "DATE":"1/06/2018" },
{ "COUNTRY":"US", "LoC":"New York", "BALANCE":"43,568", "DATE":"18/05/2018" },
{ "COUNTRY":"PL", "LoC":"Kraków", "BALANCE":"12,362", "DATE":"22/06/2018" },
{ "COUNTRY":"AU", "LoC":"Townsville", "BALANCE":"7,569", "DATE":"1/07/2018" },
{ "COUNTRY":" ", "LoC":"BALANCE:", "BALANCE":"142,072", "DATE":" " }
];
var table = document.getElementById('gable');
data.forEach(function(object) {
var tr = document.createElement('tr');
tr.innerHTML = '<td>' + object.COUNTRY + '</td>' +
'<td>' + object.LoC + '</td>' +
'<td>' + object.BALANCE + '</td>' +
'<td>' + object.DATE + '</td>';
table.appendChild(tr);
});
</script>
There are a lot more lines of data, the table has CSS styling and applies the sortTable(n) function to the Headers. It displays perfectly, looks and functions like we want,
We've Googled [lots] and tried various load / populate scripts and attempted to get the example on w3schools working - https://www.w3schools.com/js/js_json_html.asp - alas we're fairly new to this.
Our JSON file /assets/sample.JSON is correctly formatted and meets the requirements.
How do we do a simple import of the JSON to populate the table id="gable"?
Ok, so in this solution I am going to assume that your external json file is called 'example.json'
Your external file should look something like this
example.json:
[
{ "COUNTRY":"UK", "LoC":"London", "BALANCE":"78,573", "DATE":"1/06/2018" },
{ "COUNTRY":"US", "LoC":"New York", "BALANCE":"43,568", "DATE":"18/05/2018" },
{ "COUNTRY":"PL", "LoC":"Kraków", "BALANCE":"12,362", "DATE":"22/06/2018" },
{ "COUNTRY":"AU", "LoC":"Townsville", "BALANCE":"7,569", "DATE":"1/07/2018" },
{ "COUNTRY":" ", "LoC":"BALANCE:", "BALANCE":"142,072", "DATE":" " }
]
The html remains the same all the changes have been made in the script tags. I split the functionality into 2 new functions. The first function (get_json_data) gets the json data from the external json file. The second function (append_json) appends the data to the table.
I have put comments throughout the code to explain what everything is doing. if you have any questions or if something is unclear let me know.
here is the code for the html file:
<div>
<p> *** OTHER STUFF HERE ***<p/>
<table id="gable">
<colgroup>
<col class="twenty" />
<col class="fourty" />
<col class="thirtyfive" />
<col class="twentyfive" />
</colgroup>
<tr>
<th onclick="sortTable(0)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspCOUNTRY</th>
<th onclick="sortTable(1)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspLOCATION</th>
<th onclick="sortTable(2)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspBALANCE</th>
<th onclick="sortTable(3)"><span class="glyphicon glyphicon-sort"></span>&nbsp&nbspDATE</th>
</tr>
</table>
</div>
<script>
//first add an event listener for page load
document.addEventListener( "DOMContentLoaded", get_json_data, false ); // get_json_data is the function name that will fire on page load
//this function is in the event listener and will execute on page load
function get_json_data(){
// Relative URL of external json file
var json_url = 'example.json';
//Build the XMLHttpRequest (aka AJAX Request)
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {//when a good response is given do this
var data = JSON.parse(this.responseText); // convert the response to a json object
append_json(data);// pass the json object to the append_json function
}
}
//set the request destination and type
xmlhttp.open("POST", json_url, true);
//set required headers for the request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// send the request
xmlhttp.send(); // when the request completes it will execute the code in onreadystatechange section
}
//this function appends the json data to the table 'gable'
function append_json(data){
var table = document.getElementById('gable');
data.forEach(function(object) {
var tr = document.createElement('tr');
tr.innerHTML = '<td>' + object.COUNTRY + '</td>' +
'<td>' + object.LoC + '</td>' +
'<td>' + object.BALANCE + '</td>' +
'<td>' + object.DATE + '</td>';
table.appendChild(tr);
});
}
</script>
you can have a function to create the table independent from your data fields:
function updateTable(tableId, jsonData){
var tableHTML = "<tr>";
for (var headers in jsonData[0]) {
tableHTML += "<th>" + headers + "</th>";
}
tableHTML += "</tr>";
for (var eachItem in jsonData) {
tableHTML += "<tr>";
var dataObj = jsonData[eachItem];
for (var eachValue in dataObj){
tableHTML += "<td>" + dataObj[eachValue] + "</td>";
}
tableHTML += "</tr>";
}
document.getElementById(tableId).innerHTML = tableHTML;
}

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>

Jquery datatable plugin not loading

Datatable was not working. Even console has no errors regarding datatables. Once the page gets loaded, the datatable plugin was not even loading. I tried with cdn links too, still the plugin was not working with my script.
Below is my sample code:
$('#newtable').dataTable( {"pagingType": "full_numbers"} );
<table class="table table-bordered table-hover" id="broker" cellspacing="0">
<thead>
<tr><th class="info">Broker</th>
<th class="info">Address</th>
</thead>
<tbody>
<tr>
<td>a</td>
<td>b</td>
</tr>
</tbody>
</table>
Scripts and css added:
<script src="-/scripts/jquery.dataTables.min.js"></script>
<link href="-/styles/datatables.css" rel="stylesheet">
<link href="-/styles/datatables.responsive.css" rel="stylesheet">
<script src="-/scripts/datatables.responsive.js"></script>
Here is the exact script I have used to populate the table and map for a page:
setTimeout(function() {
$(document).ready(function() {
// Search button clicked
$('#btnSearch').click(function(e) {
e.preventDefault();
$('#searchUserLongitude').val("");
$('#searchUserLatitude').val("");
// Do an AREA search
getBrokerSearchList('AREA');
});
// Hide certain text/functions if geo-location is not available
if (window.navigator.geolocation) {
window.navigator.geolocation.getCurrentPosition(function(position) {
$("#findAdvisor").removeClass("hide");
$("#findAdvisorOr").removeClass("hide");
$("#findAdvisorText").removeClass("hide");
$('#searchGpsAvailable').val("Y");
}, function() {
//do nothing.
});
}
});
}, 1000);
function openInfo(agentCode, lat, lng) {
var googleMap = this.APP.instances.googleMap;
googleMap.openInfo(agentCode, lat, lng);
window.location = '#map';
}
function glSuccess(lat, lon) {
$('#searchUserLongitude').val(lon);
$('#searchUserLatitude').val(lat);
$('#searchTownStreet').val("");
$('#searchPostCode').val("");
$('#searchPostCode').trigger('render.customSelect'); // Update the dropdown
// Do a GPS search
getBrokerSearchList('GPS');
}
/*
* Function to call if the browser doesn't support geoLocation or the
* user declines to send their position
*/
function glFail() {
alert('Sorry. Either your browser does not support geoLocation, or you refused the request.');
}
// Get the fund prices
function getBrokerSearchList(typeOfSearchRequested) {
$("#advisorFinder").addClass("hidden");
$("#finalSection").addClass("invisible");
$("#messagePleaseWait").removeClass("hidden");
$("#messageError").addClass("hidden");
$("#messageNotFound").addClass("hidden");
$("#messageErrorService").addClass("hidden");
var searchTownStreet = $("#searchTownStreet").val();
var searchPostCode = $("#searchPostCode").val();
var searchUserLatitude = $("#searchUserLatitude").val();
var searchUserLongitude = $("#searchUserLongitude").val();
var searchGpsAvailable = $("#searchGpsAvailable").val();
// AJAX call to get advisor search data (JSON), and update the page based on it
$.ajax({
type: 'POST',
url: '/services/findAdvisors?searchTypeOfSearchRequested=' + encodeURIComponent(typeOfSearchRequested) + '&searchTownStreet=' + encodeURIComponent(searchTownStreet) + '&searchPostCode=' + encodeURIComponent(searchPostCode) + '&searchUserLatitude=' + encodeURIComponent(searchUserLatitude) + '&searchUserLongitude=' + encodeURIComponent(searchUserLongitude) + '&searchGpsAvailable=' + encodeURIComponent(searchGpsAvailable),
dataType: "json", //to parse string into JSON object,
success: function(data) {
if (data) {
if (data.errors) {
// We got data back from the service, but there are errors
// Show/hide the appropriate sections
$("#advisorFinder").removeClass("hidden");
$("#messagePleaseWait").addClass("hidden");
var htmlErrors = "<div class='alert alert-danger custom-alert'>";
var displayErrors = false;
// Loop over all of the errors returned and attempt to deal with each one individually
for (var prop in data.errors) {
htmlErrors = htmlErrors + "<p>" + data.errors[prop].toString() + "</p>";
displayErrors = true;
}
htmlErrors = htmlErrors + "</div>";
if (displayErrors) {
$("#messageErrorService").empty().append(htmlErrors);
$("#messageErrorService").removeClass("hidden");
}
// Tidy up the boxes
$(window).trigger('resize');
} else {
// Update the search results
var lenAdvisorList = data.findAdvisorResultList.length;
var htmlAdvisorList = "";
var protocol = "";
if (lenAdvisorList > 0) {
// We have results
// Build the HTML
htmlAdvisorList += "<div class='box-simple'>";
htmlAdvisorList += "<div class='content' style='padding:5px'>";
htmlAdvisorList += "<div class='table-wrapper' style='margin-top: 15px;'>";
htmlAdvisorList += "<table cellspacing='0' class='table table-bordered table-hover datatables' id='broker'>";
htmlAdvisorList += "";
// Add the table header
htmlAdvisorList += "<thead>";
htmlAdvisorList += "<tr>";
htmlAdvisorList += "<th class='info'>Broker</th>";
htmlAdvisorList += "<th class='info'>Address</th>";
htmlAdvisorList += "<th class='info'>Phone</th>";
htmlAdvisorList += "<th class='info'></th>";
htmlAdvisorList += "</tr>";
htmlAdvisorList += "</thead>";
// Add the table rows
for (var i = 0; i < lenAdvisorList; i++) {
if (data.findAdvisorResultList[i].agentNumber) {
htmlAdvisorList += "<tr data-unqcode=" + data.findAdvisorResultList[i].agentNumber + " data-address=" + data.findAdvisorResultList[i].address + " data-location=" + data.findAdvisorResultList[i].brokerLatitude + "," + data.findAdvisorResultList[i].brokerLongitude + ">";
htmlAdvisorList += "<td>" + data.findAdvisorResultList[i].agency + "</td>";
htmlAdvisorList += "<td>" + data.findAdvisorResultList[i].address + "</td>";
htmlAdvisorList += "<td><a href='tel:" + data.findAdvisorResultList[i].workphone + "'>" + data.findAdvisorResultList[i].workphone + "</a></td>";
htmlAdvisorList += "<td width='32'>";
htmlAdvisorList += "<a id='" + data.findAdvisorResultList[i].agentNumber + "' href='#'><img width='32' height='32' src='-/assets/elements/icon_map.png'></a>";
htmlAdvisorList += "<div class='hidden'>";
htmlAdvisorList += "<div class='info-window'>";
htmlAdvisorList += "<p><strong>" + data.findAdvisorResultList[i].agency + "</strong></p>";
htmlAdvisorList += "<p>Address: <strong>" + data.findAdvisorResultList[i].address + "</strong></p>";
htmlAdvisorList += "<p>Phone: <strong>" + data.findAdvisorResultList[i].workphone + "</strong></p>";
htmlAdvisorList += "<p>Email: <strong>" + data.findAdvisorResultList[i].email + "</strong></p>";
if (data.findAdvisorResultList[i].website != '' && data.findAdvisorResultList[i].website.substring(0, 4) != 'http') {
protocol = "http://";
} else {
protocol = "";
}
htmlAdvisorList += "<p><strong>Website:</strong> <a target='_blank' href='" + protocol + data.findAdvisorResultList[i].website + "'>" + data.findAdvisorResultList[i].website + "</a><br/></p>";
htmlAdvisorList += "</div>";
htmlAdvisorList += "</div>";
htmlAdvisorList += "</td>";
htmlAdvisorList += "</tr>";
}
}
// Clear the existing HTML for the results list
$('#resultsList').empty();
// Show the new HTML + other page updates
if (htmlAdvisorList != "") {
$("#resultsList").append(htmlAdvisorList);
$("#advisorFinder").removeClass("hidden");
$("#finalSection").removeClass("invisible");
$("#messagePleaseWait").addClass("hidden");
$("#messageNotFound").addClass("hidden");
// Initialise the map
// Will read the data from the table and populate the map
// Must happen before the datatables update
APP.instances.googleMap.init();
// Initialse the datatables
$('#broker').dataTable({
"pagingType": "full_numbers"
});
}
// Tidy up the boxes
$(window).trigger('resize');
} else {
// We don't have results
// Clear the existing HTML for the results list
$('#resultsList').empty();
$("#advisorFinder").removeClass("hidden");
$("#finalSection").removeClass("invisible");
$("#messagePleaseWait").addClass("hidden");
$("#messageNotFound").removeClass("hidden");
// Initialise the map
APP.instances.googleMap.init();
// Tidy up the boxes
$(window).trigger('resize');
}
}
}
},
error: function(jqXHR, textStatus, errorThrown) {
// We got an error during the AJAX call
// Clear the existing HTML for the results list
$('#resultsList').empty();
$("#advisorFinder").removeClass("hidden");
$("#finalSection").removeClass("invisible");
$("#messagePleaseWait").addClass("hidden");
$("#messageError").removeClass("hidden");
$("#messageNotFound").addClass("hidden");
// Initialise the map
APP.instances.googleMap.init();
// Tidy up the boxes
$(window).trigger('resize');
}
});
}
The reason is because you're using the wrong table ID. You declared the table with "broker":
<table class="table table-bordered table-hover" id="broker" cellspacing="0">
But then instantiate the DataTable with "newtable":
$('#newtable').dataTable( {"pagingType": "full_numbers"} );
The solution is to change your line to be:
$('#broker').dataTable( {"pagingType": "full_numbers"} );
Any time you're having issues with a library not working as expected, it's usually a good idea to double check the links you're using to request the library. You'll also want to make sure your table markup is correct as well. Lastly, the table id in your html needs to be the same as the selector you use to initialize the table features in your jQuery.
The solution below resolves these issues and works. Hope this helps!
$(document).ready(function() {
$('#broker').DataTable({
"pagingType": "full_numbers"
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet" />
<table id="broker" class="display table table-bordered table-hover" style="width:100%" cellspacing="0">
<thead>
<tr>
<th>Broker</th>
<th>Address</th>
</tr>
</thead>
<tbody>
<tr>
<td>a</td>
<td>b</td>
</tr>
<tr>
<td>c</td>
<td>d</td>
</tr>
<tr>
<td>e</td>
<td>f</td>
</tr>
</tbody>
<tfoot>
<tr>
<th>Broker</th>
<th>Address</th>
</tr>
</tfoot>
</table>