Update Data for Bootstrap datatable - javascript

I want to implement a Datatable into a theme, which gets the data via an Ajax Request. Once the document is loaded, I build the HTML part for the datatable. The problem is: Once I click a sort function (for example sort one row ascending) it uses the original data to sort (which is given in the .php file) instead of the new JQuery loaded datatable. So probably I need to reinitialize the datatable or anything else?
HTML Part:
<tbody id="accountList">
<!-- List all accounts -->
<tr>
<td>username#hostname-de</td>
<td>PS</td>
<td>350000</td>
<td>45000</td>
<td>Victor Ibarbo</td>
<td>30 / 30</td>
<td>224500</td>
<td><label class="label label-success">Online</label></td>
</tr>
</tbody>
JQuery part:
function buildAccountList(){
$.ajax({
url: "/database/accounts.php",
type: "POST",
data: {action: "selectAccounts"},
success: function (response) {
var opt = '';
$.each(response, function(i, e){
opt +='<tr>';
opt += '<td>' + e.email + '</td>';
opt += '<td>' + e.platform + '</td>';
opt += '<td>' + e.coins + '</td>';
opt += '<td>' + e.password + '</td>';
opt += '<td>' + e.tradepileCards + '</td>';
opt += '<td>' + e.tradepileValue + '</td>';
opt += '<td>' + e.enabled + '</td>';
opt += '</tr>';
});
$('#accountList').html(opt);
},
dataType: "json"
});
}
The creation of the table works fine, but as I described, once I press a sort function it uses the old table (given by the html file).

Related

Ajax Data Display fetched from Database

I have a data coming from the database. And Displaying when the ajax function is called. I am able to display it. But, One of the variable is an array data and saved it using implode function. Data is like (a,b,c,d).
Data is displaying in the below format
data1 Data2 Data3 (a,b,c,d) Data5 and so on.
I want to explode the array data and print one below the another.
I should display it like
data1 data2 data3 a data5
b
c
d
Here is the code which i am written to get the data.
<script type="text/javascript">
$('#genreport').on('click',function(){
var Representativeid = document.getElementById("Representativeid").value;
var dateFrom = document.getElementById("dateFrom").value;
var dateTo = document.getElementById("dateTo").value;
var url = '{{URL::to('/admin/GenReport')}}';
$.ajax({
type : 'get',
url : url,
data : {Representativeid:Representativeid,dateFrom:dateFrom,dateTo:dateTo},
success:function(data){
console.log(data);
var $tabledata = $('#tbody');
$tabledata.empty();
for (element in data)
{
var row = '<tr>' +
'<td>' + data[element].date + '</td>'+
'<td>' + data[element].doctor_name + '</td>'+
'<td>' #foreach(explode(',', data[element].products ) as $product)
{{$product}}
#endforeach '</td>' +
'<td>' + data[element].quantity + '</td>'+
'<td>' + data[element].locations +'</td>'+
'<td>' + data[element].area + '</td>'+
'</tr>';
$('#tbody').append(row);
}
},
error:function(data)
{
alert('fail');
alert(data);
}
});
});
</script>
I am failing in the for-each logic. Please help me to display as i expected.
You cannot use a php function/code(server-side) in your javascript/jQuery code(client-side), as the php code will be parsed before the page is loaded. Instead you need to use javascript code.
First, you need to split the value into an array
var productsArray = data[element].products.split(',');
then you would need to get the array count (.length) to use a rowspan, so it doesn't break your table stucture
var rowSpan = productsArray.length;
....
'<td rowspan="'+rowSpan+'">' + data[element].date + '</td>'+
....
finally, you need to loop in javascript, not php, through the array. (note, because the i<0 <td>s go on subsequent rows, you need to add them after)
var rowAfter = "";
for (var i = 0; i < rowSpan; i++) {
if(i == 0) {
row += '<td>' + productsArray[i] + '</td>';
} else {
rowAfter += '<tr><td>' + productsArray[i] + '</td></tr>';
}
}
so it would look something like this -
for (element in data)
{
// get products into an array
var productsArray = data[element].products.split(',');
// get products array count
var rowSpan = productsArray.length;
var row = '<tr>' +
'<td rowspan="'+rowSpan+'">' + data[element].date + '</td>'+
'<td rowspan="'+rowSpan+'">' + data[element].doctor_name + '</td>';
// loop through products array
var rowAfter = "";
for (var i = 0; i < rowSpan; i++) {
if(i == 0) {
row += '<td>' + productsArray[i] + '</td>';
} else {
rowAfter += '<tr><td>' + productsArray[i] + '</td></tr>';
}
}
row +=
'<td rowspan="'+rowSpan+'">' + data[element].quantity + '</td>'+
'<td rowspan="'+rowSpan+'">' + data[element].locations +'</td>'+
'<td rowspan="'+rowSpan+'">' + data[element].area + '</td>'+
'</tr>';
// append both row and the <td>s in rowAfter
$('#tbody').append(row+rowAfter);
}
just add <tr><td> inside foreach.
Edit:
Also, take a look at this link. table inside a td

Adding a href to an Ajax generated table in html

I have implemented this with thymeleaf before and have struggled to implement it with javascript and Ajax get request.
Basically the table is generated and in my html script the Ajax get request gets and displays a list of teams into this table, is there a way to include a href or even a button after each row that passes the teams Id to my controller upon clicking the link?
Here is my controller:
$(document).ready(function() {
// DO GET
$.ajax({
type : "GET",
url : "/all",
success: function(result){
$.each(result, function(i, team){
var customerRow = ' <tr>' +
'<td>' + team.id + '</td>' +
'<td>' + team.teamName.toUpperCase() + '</td>' +
'<td>' + team.teamAddress + '</td>' +
'<td>' + team.level + '</td>' +
'<td>' + '' + View Team + '</td>' +
'</tr>';
$('#customerTable tbody').append(customerRow);
});
$( "#customerTable tbody tr:odd" ).addClass("info");
$( "#customerTable tbody tr:even" ).addClass("success");
},
error : function(e) {
alert("ERROR: ", e);
console.log("ERROR: ", e);
}
});
// do Filter on View
$("#inputFilter").on("keyup", function() {
var inputValue = $(this).val().toLowerCase();
$("#customerTable tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(inputValue) > -1)
});
});
})
You can see my attempt to implement it at the 5th <td> tag.
This will be the controller I am passing the id variable to, just incase.
#RequestMapping(value="/viewteam/{id}", method=RequestMethod.GET)
public String ViewTeam(Model model, #PathVariable Long id) {
Team team = teamRepository.findOne(id);
//the code below should ideally return all the players associated with the above team id in an array list, this array list will be passed via thymeleaf to display all players
model.addAttribute("team", team);
return "singleteam";
}
Looks like you may be over complicating this using the inline .Net syntax. Considering you already have the data back from the ajax you should be able to set the string (like #Musa mentioned) like this:
'<td>View Team</td>' +
Just as a robust example:
var team = {
id: 1,
teamName: "Capitals",
teamAddress: "Capital One Arena",
level: 9001,
};
var customerRow = ' <tr>' +
'<td>' + team.id + '</td>' +
'<td>' + team.teamName.toUpperCase() + '</td>' +
'<td>' + team.teamAddress + '</td>' +
'<td>' + team.level + '</td>' +
'<td>' + 'View Team</td>' +
'</tr>';
$('#customerTable tbody').append(customerRow);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="customerTable">
<tbody>
</tbody>
</table>

How to retrieve JSON file data using ajax and when the user clicks on the button the content displays in table?

I am trying to generate a table dynamically and then sort the elements of that table in my webpage but from the JSON file I am not able to retrieve the data
on the click of the button to generate the table. Can I get to know where I am wrong with my code.
// teamdetail.json file data:
{
"teamList": [{
"date": "24/07/2016",
"venue": "Bengaluru",
"matchdetails": "Qualifier 1 ? Gujarat Lions vs Royal Challengers Bangalore"
}, {
"date": "25/07/2016",
"venue": "Delhi",
"matchdetails": "Eliminator ? Sunrisers Hyderabad vs Kolkata Knight Riders"
},
{
"date": "27/07/2016",
"venue": "Bengaluru",
"matchdetails": "Qualifier 2 ? Q1 Loser vs EL Winner"
}
]
}
$(document).ready(function() {
$("#getdetail").click(function() {
$.getJSON('teamdetail.json', function(data) {
var detail = '<tr><th colspan = 3>Playoff Team Schedule</th></tr>' +
'<tr><th>Date</th><th>Venue</th><th>Match Details</th></tr>';
$.each(data, function(key, value) {
detail += '<tr>';
detail += '<td>' + value.date + '</td>';
detail += '<td>' + value.venue + '</td>';
detail += '<td>' + value.matchdetails + '</td>';
detail += '</tr>';
});
$('#teamdetail').append(detail);
});
});
});
<button type="button" id="getdetail">Get Team Details</button>
<table id="teamdetail"></table>
Your issue is because your JSON response is not an array - its an object with a property teamList which is the array you want to loop over.
If you replace $.each(data, ...) with $.each(data.teamList, ...) it should work fine.
You have to loop over data['teamList']
$(document).ready(function() {
$("#getdetail").click(function() {
$.getJSON('teamdetail.json', function(data) {
var detail = '<tr><th colspan = 3>Playoff Team Schedule</th></tr>' +
'<tr><th>Date</th><th>Venue</th><th>Match Details</th></tr>';
$.each(data['teamList'], function(key, value) {
detail += '<tr>';
detail += '<td>' + value.date + '</td>';
detail += '<td>' + value.venue + '</td>';
detail += '<td>' + value.matchdetails + '</td>';
detail += '</tr>';
});
$('#teamdetail').append(detail);
});
});
});
I hope it should help you Cheers!

Data disappears when we click on column name in datatable and showing 'No data available in table'

I am trying to populate the table data in datatable
Sample Code:
HTML:
<table id="idOfmyTable">
<thead>
<tr>
<th>Column1</th>
<th>Column2</th>
<th>Column3</th>
<th>Column4</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Used Jquery Library:
jquery.dataTables.min.css
jquery-3.1.0.min.js
jquery.dataTables.min.js
Javascript:
function getAllRecords(rootPath) {
$.getJSON(rootPath , function(response) {
$("#idOfmyTable").find('tbody').empty(); // Added to remove "No data available in table" message in first row after loading data
$.each(response, function(idx, obj) {
var body = "<tr>";
body += "<td>" + obj.column1 + "</td>";
body += "<td>" + obj.column2 + "</td>";
body += "<td>" + obj.column3 + "</td>";
body += "<td>" + obj.column4 + "</td>";
body += "</tr>";
$( "#idOfmyTable tbody" ).append(body);
});
$('#idOfmyTable').DataTable();
});
}
Data is populating in datatable with below issues:
'Showing 0 to 0 of 0 entries' Showing even though there is a data in
datatable.
When i click on any column head(for sorting) the data will be disappeared and "No data available in table" message will be
displayed.
Please help me on this, what i am doing wrong here?
Note: I followed here, but no luck.
I faced the exact same issue. Now resolved it.
In my case the data in the table is populating in the ajax call success function.
I instantiated dataTable before the ajax call, which was creating issue, now I have instiated dataTable in the success function of ajax call which resolved issue for me.
$.ajax({
url: "DeviceController/viewAllDevices",
type: "post",
dataType: "json",
success: function (data) {
// console.log(data[0]['SRNO']);
var tbody = "";
for (var i in data) {
tbody += '<tr>';
tbody += '<td>' + data[i]['SRNO'] + '</td>';
tbody += '<td>' + data[i]['ID'] + '</td>';
tbody += '<td>' + data[i]['DEVCATEGORY'] + '</td>';
tbody += '<td>' + data[i]['CITY'] + '</td>';
tbody += '<td>' + data[i]['DEVNAME'] + '</td>';
tbody += '<td>' + data[i]['DEVURL'] + '</td>';
tbody += '<td>' + data[i]['DEVUSRNAME'] + '</td>';
tbody += '<td>' + data[i]['DEVPASS'] + '</td>';
tbody += '<td style="text-transform:uppercase;">' + data[i]['STATUS'] + '</td>';
tbody += '<td>' + data[i]['OPERATOR'] + '</td>';
tbody += '<td>' + data[i]['DATETIME'] + '</td>';
tbody += '<td>' + data[i]['CHANGEOPERATOR'] + '</td>';
tbody += '<td>' + data[i]['CHANGETIME'] + '</td>';
tbody += `<td>
<button id="delbtn" class="btn btn-danger" value="${data[i]['ID']}">Delete</button>
</td>`;
tbody += `<td>
<button onclick="myFunction()" id="editbtn" class="btn btn-success" value="${data[i]['ID']}">Edit</button>
</td>`;
tbody += '</tr>';
}
$("#tbody").html(tbody);
**$('#transacTable').DataTable({
"aLengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
dom: 'Blfrtip',
buttons: ['csv']
});**
}
});

Displaying data from json file

I'm trying to get content from a json file, but until now I get nothing.
I have the status connection == 200 and I can see the content in the chrome console
but I get nothing when I try to display the data to html table, but when I use the same jquery code with api from another service like import.io things works fine.
Can you tell me what am I doing wrong?
This api is from kimonolabs.
$(document).ready(function () {
var tabel = '<table><THEAD><caption>Calendário</caption></THEAD>';
tabel += '<th>' + 'Hora' + '</th>' + '<th>' + 'Equipas' + '</th><th>' + 'jornda' +
'</th><th>' + 'Data' + '</th>';
$.ajax({
type: 'GET',
url: 'https://api.myjson.com/bins/1dm6b',
dataType: 'json',
success: function (data) {
console.log(data);
$('#update').empty();
$(data.m_Marcadores).each(function (index, value) {
tabel += '<tr><td>' + this.posicao + '</td>' + '<td>' + this.golos + '</td></tr>';
}); //each
tabel += '</table>';
$("#update").html(tabel);
} //data
}); //ajax
}); //ready
According to JSON structure you should iterate over data.results.m_Marcadores array:
$(data.results.m_Marcadores).each(function (index, value) {
tabel += '<tr><td>' + this.posicao + '</td><td>' + this.golos + '</td></tr>';
});
Another problem. In header of the table you setup 4 colums, but in loop you are creating only two of them. Number of header columns should be the same as other row td.
Also you need to wrap th elements in tr. For example, fixed table header:
var tabel = '<table>' +
'<THEAD><caption>Calendário</caption></THEAD>' +
'<tr>' +
'<th>Hora</th><th>Equipas</th><th>jornda</th><th>Data</th>' +
'</tr>';
Demo: http://jsfiddle.net/onz02e43/

Categories

Resources