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). I hope you guys can help me.
Are you using the jQuery DataTables plug-in? If so, they already have built-in functionality for ajax data sources: DataTables with AJAX
Alternatively, I think you should rather try to modify the table data itself in javascript instead of the rendered HTML. Using the DataTable API, especially table.clear(), table.rows.add() followed by a table.draw()(also check here), you should be able to update the data properly and use the order functionality afterwards.
In response to the comment:
Basically something like this should be enough as an initialization of the datatable:
$(document).ready(function() {
$('#example').dataTable( {
"ajax": 'your url here'
});
});
Then your json should be organized as:
{
"data": [
[
'your columns',
...
],
]
}
If you want to not name the top-level key of your data 'data' you could set it by initializing with
"ajax": {
"url": "data/objects_root_array.txt",
"dataSrc": "your top-level key (or nothing for a flat array"
}
And as last option you can use objects instead of arrays in your ajax by adding a columns option to the initialization:
"ajax": ...,
"columns": [
{ "data": "email" },
{ "data": "platform" },
{ "data": "coins" },
...
]
and return json with objects like that:
{
"email": "some#email.com",
"platform": "PS",
"coins": "320,800",
...
}
By the way, using this you would not even have to add a tbody to the table in the first place at it should be automatically be created by the plugin once it gets the AJAX data.
Related
Hi i having a scenario where i am generating a dynamic table along with the dynamic button and when ever user clicks that button it has to get that row value and it has generate another dynamic table by taking this value as parameter .Till now i tried generating a dynamic table and with button and passed a parameter to that function here i stuck how to pass /accept a parameter to that function so that by using ajax call it can generate another dynamic table.
$.ajax({
type: 'GET',
url: xxxx.xxxxx.xxxxx,
data: "Id=" + clO + Name_=" + cl+ "",
success: function (resp) {
var Location = resp;
var tr;
for (var i = 0; i < Location.length; i++) {
tr = tr + "<tr>
tr = tr + "<td style='height:20px' align='right'>" + Location[i].Amount + "</td>";
tr = tr + "<td style='height:20px' align='right'>" + Location[i].Name + "</td>";
tr = tr + '<td><input type="button" class="nav_button" onclick="test(\'' + Location[i].Amount + '\',\'' + Location[i].Name + '\')"></td>';
tr = tr + "</tr>";
};
document.getElementById('d').style.display = "block";
document.getElementById('Wise').innerHTML = "<table id='rt'>" + "<thead ><tr><th style='height:20px'>Amount</th>" + "<th style='height:20px'>Name</th>""</tr></thead>"
+ tr + "<tr><td align='left' style='height:20px'><b>Total:"+ TotBills +"</b></td><td style='height:20px' align='right'><b></b></td></tr>" +
"</table>";
document.getElementById('Wise').childNodes[0].nodeValue = null;
},
error: function (e) {
window.plugins.toast.showLongBottom("error");
}
function test(value,val1,val2) {
navigator.notification.alert(value + ";" + val1 + ";" + val2);
// here i have to pass the another ajax by basing on the the onclick
}
so here in the function i have to pass the parameters and have to display in the new page and how is it possible ?
To pass data from a page to another your best bet is localStorage and SessionStorage;
SessionStorage - Similar to a cookie that expires when you close the browser. It has the same structure as the localStorage, but there is no way to change its permanence time, whenever closing will be deleted.
LocalStorage - This is similar to a cookie, but it never expires, so while there were records in the AppCache for that domain, the variable will exist (unless the user creates a routine to remove it).
Both attributes were added by HTML5. The above items called web storage. But there are other forms of local storage through HTML5, such as WebSQL database, Indexed Database (IndexDB), as well as conventional files (File Access).
Ex:
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");
Is it what you meant ?
It's unclear what you're after, but I think I see where you're headed. From the code you included, it seems like you want something like this instead:
// This will take the user to a separate page, passing your parameters
function test(val1,val2) {
window.location.href("/UrlGoesHere?Amount=" + val1 + "&Name=" + val2);
}
Another option, based on what you've said, is to redraw the table. You could do that with something like this:
function test(val1,val2) {
$.ajax({
type: 'GET',
url: "/UrlGoesHere",
data: "Amount=" + val1 + "&Name=" + val2,
success: function (resp) {
// redraw table here
}
});
}
I have a jQuery's datatable which gets filled up with server side data like this:
"columns": [
{
"targets": -1,
"data": "ImageURL",
"name": "Title",
"render": function (data, type, row) {
return '<td><div class="tableimage"><img src="' + data + '"/></div></td>'; //'<td><img src=' + data + '></td>';
}
},
{
"data": "Title",
"name": "Title",
"render": function (data, type, row) {
return '<td>' + data + '</td>';
}
},
{
"data": "CurrentPrice",
"name": "CurrentPrice",
"render": function (data, type, row) {
return '<td>$ ' + data + '</td>';
}
},
]
And this is fine, each column gets generated and rendered in my browser like this:
<tr>
// generated td's here...
<tr>
Now my question here is whether I can generate a custom tr tag with specially added class?
Something like this:
<tr class="myclassNameGoesHere">
</td>
Is this doable via server side data processing & jquery's datatables ?
P.S. I tried something like this:
$(row).addClass("alert-danger");
// or
row.className = "alert-danger";
But neither of these worked... :/
Firstly, you don't need to return td tags in render functions, datatables automatically created td tags for you.
So,
return '<td>' + data + '</td>';
would become
return data;
Now, to answer your question, use createdRow callback provided by datatables.
Like,
$('#example').dataTable( {
"createdRow": function( row, data, dataIndex ) {
$(row).addClass( 'alert-danger' );
}
} );
Currently working on jQuery auto complete where I can able to generate data from JSON single column data, but I want two values should be displayed label and descirption
this is my json
[{"id":"Emirates College of Technology- UAE","label":"COL000001","value":"COL000001"}, {"id":"Al Khawarizmi nternational ollege- UAE","label":"COL000002","value":"COL000002"}, {"id":"Syscoms ollege","label":"COL000003","value":"COL000003"}, {"id":"Abounajm Khanj Pre-Uni enter","label":"COL000004","value":"COL000004"}, {"id":"Advanced lacement","label":"COL000005","value":"COL000005"}, {"id":"Al Buraimi College Uni Clge)","label":"COL000006","value":"COL000006"}, {"id":"Al-Ain Community ollege","label":"COL000007","value":"COL000007"}, {"id":"AMA Computer ollege","label":"COL000008","value":"COL000008"}, {"id":"Arab Academy for Bankg nd Fin","label":"COL000009","value":"COL000009"}, "id":"ARABACDSCITECHMARTIMETRNS","label":"COL0000010","value":"COL0000010"}, "id":"Arapahoe Community College","label":"COL0000011","value":"COL0000011"}, {"id":"Other","label":"Other","value":"Other"}]
Here is my jquery code
$("#scl_name").autocomplete({
highlightClass: "bold",
source: function( request, response ) {
var regex = new RegExp(request.term, 'i');
//var filteredArray = filteredArray.slice(0,10);
$.ajax({
url: "json/dummy.json",
dataType: "json",
data: {term: request.term},
success: function(data) {
response($.map(data, function(item) {
if(regex.test(item.label)){
var html="";
html += "<table>";
html += " <tr>";
html += " <td>"+addslashes(item.label)+"</td>";
html += " <td>"+addslashes(item.id)+"</td>";
html += " </tr>";
html += "</table>";
return {
value: html,
value: item.id,
value: item.label
};
}
}));
},
});
},
select: function(event, ui) {
$('#school_Name').val(ui.item.id);
}
});
});
function addslashes(string) {
return string.replace(/\\/g, '\\\\').
replace(/\u0008/g, '\\b').
replace(/\t/g, '\\t').
replace(/\n/g, '\\n').
replace(/\f/g, '\\f').
replace(/\r/g, '\\r').
replace(/'/g, '\\\'').
replace(/"/g, '\\"');
}
With this above code I am getting the data, for first column but not for second column in second column i am getting the value as undefined
what I am doing wrong here?
ReferenceError: Item is not defined
html += " <th>" + Item + "</th>";
Well, here it goes my help. When dealing with JSON is better if you can be sure that you are receiving what you are expecting, first of all. To do this you have a function called .success on your AJAX response and this parses each JSON item (this will be your first item: {"id":"Emirates College of Technology- UAE","label":"COL000001","value":"COL000001"})
To be sure you are receiving the id, label and value elements I will do something like this inside your success function:
console.log(item.id);
console.log(item.label);
console.log(item.value);
or just directly
console.log(item); // this will be presented as an object you can examine on your chrome browser, for example.
if you are sure you are getting the values on the client then I will be fixing the problem you are having when returning from the function, as you may know you can only return one value, not three:
return {
value: html,
value: item.id,
value: item.label
};
Change it to :
return {
value: html,
};
as you seem to be creating the entire value already. If this is not your issue, please post back again.
If you want to add a heading this will do it:
var html = "";
html += "<table>";
html += " <tr>";
html += " <th>" + Title + "</th>";
html += " <th>" + Description + "</th>";
html += " </tr>";
html += " <tr>";
html += " <td>" + addslashes(item.label) + "</td>";
html += " <td>" + addslashes(item.id) + "</td>";
html += " </tr>";
html += "</table>";
I use jQuery DataTables in my application.
I want my application be accessed by mobile devices. I implement http://jsfiddle.net/ryanoc/ebRXw/ in my application. But the button can not be displayed. The data look like this : [object Object]
I use render option in jQuery DataTables to display the button
"render": function(data, type, full ){
var btn = '<i class="fa fa-edit"></i> Edit ';
return btn;
},
SOLUTION
Add the following option to your DataTables initialization code.
responsive: {
details: {
type: 'inline',
renderer: function (api, rowIdx) {
var theRow = api.row(rowIdx);
var data = api.cells(rowIdx, ':hidden').eq(0).map(function (cell) {
var header = $(api.column(cell.column).header());
return '<tr>' +
'<td><b>' +
header.text() + ':' +
'</b></td> ' +
'<td>' +
$( api.cell( cell ).node() ).html() +
'</td>' +
'</tr>';
}).toArray().join('');
return data ?
$('<table/>').append(data) :
false;
}
}
}
DEMO
See this jsFiddle for code and demonstration.
Ok, so I have a table with each row having check boxes at the start of each table row. When a user clicks the table rows he/she wants to display and hits the submit button I want those table rows to show up on another page. I am doing this by creating a variable just like this:
$('#submit').click(function(){
var data;
var title = $('#dimTableTitle td').html();
data = '<table id="dimTable">';
data += '<tbody>';
data += '<tr id="dimTableTitle">' + '<td colspan="100">' + title + '</td>' + '</tr>'
data += '<tr id="dimHeading">';
$("#dimHeading").find('td').each(function(){
data += '<td>' + $(this).html() + '</td>';
});
$('#dimTable tr').has(':checkbox:checked').each(function(){
data += '<tr>'
$(this).find('td').each(function(){
data += '<td>' + $(this).html(); + '</td>'
});
data += '</tr>'
});
data += '</tr>'
data += '</tbody>';
data += '</table>';
});
The variable 'data' displays just fine on the original page but when I try and load it into a new div or other container on a different page I only receive the entire table, not the selected table rows. I want to display that new variable onto a new page that pops up when a user clicks on the submit button. Any help would be appreciated.
You can send data with post method, (async)
jQuery.ajax({
url: "a.php?" + params,
async: false,
cache: false,
dataType: "html",
success: function(html){
returnHtml = html;
}
});
Note 1: Source code is written just to give you ideas.
Local storage is the way to go.
http://www.w3schools.com/html/html5_webstorage.asp