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.
Related
It's my first time using json and I'm trying to make an update button on a table that i make with ajax json, there is a problem that i can't put id_news attribute on the tag along with the target link. I tried put it next to the target link, but it doesn't work, and even the tables doesn't show anything, is there any way to make it work?
$(document).ready(function() {
display_data_info();
function display_data_info() {
$.ajax({
type: 'ajax',
url: '<?php echo base_url()?>/information/data_read_info',
async: false,
dataType: 'json',
success: function(data) {
var html = '';
var i;
var no;
var id_news;
for (i = 0; i < data.length; i++) {
no = +1;
html += '<tr>' +
'<td>' +
no +
'</td>' +
'<td>' +
data[i].news_title +
'</td>' +
'<td>' +
data[i].news_info +
'</td>' +
'<td>' +
data[i].news_status +
'</td>' +
'<td><a href="<?php echo site_url("information/display_update_info/".data[i].id_news); ?>" class="btn btn-app">' +
'<i class="fas fa-edit"></i> ' +
'</a>' +
'</td>' +
'</tr>';
}
$('#show_data_info').html(html);
}
});
}
});
[wanted to post just a comment, but haven't enough reputation yet. Perhaps a moderator can change my feedback into a comment?]
I see multiple typos and mistakes here:
In the first php part, put a ; after base_url()
You are not initializing no before you do no += 1
Instead of no += 1 you do no = +1 (which may accidentally overcome the previous error but it's probably not what you want)
In the <td><a href=.... line you are mixing up single and double quotes
In that same line, your javascript variable is inside PHP. data[i].id_news does not exist in PHP scope.
Check your web console and PHP error log, there will be several errors.
i'm creating a datatable for insert, update. edit event will fire on the click of but it is not firing any event on click, even the debug is not pointing toward it on click.
function GetLoginData() {
$.ajax({
url: '/LoginMaster/GetLoginData',
type: 'get',
dataType: 'json',
success: function (result) {
var GetLoginData = result;
//$('#tblLoginMaster').DataTable.clear();
//$('#tblLoginMaster').DataTable.destroy();
// table.empty();
if (GetLoginData != '') {
var str = "";
$.each(GetLoginData, function (index, obj) {
var GetID = obj.Id == null ? "" : obj.Id;
var GetName = obj.Name == null ? "" : obj.Name;
var GetEmailID = obj.Email == null ? "" : obj.Email;
var GetPassword = obj.Password == null ? "" : obj.Password;
var GetRole = obj.Role == null ? "" : obj.Role;
This is where my editstyle class is
str += "<tr class='EditStyle' data-target='#addUserModal' data-toggle='modal' value='" + GetID +"'>";
str += "<td>" + GetID + "</td>";
str += "<td>" + GetName + "</td>";
str += "<td>" + GetEmailID + "</td>";
str += "<td>" + GetPassword + "</td>";
str += "<td>" + GetRole + "</td>";
str += "</tr>"
$('#tblbodyLoginMaster').html(str);
});
$('#tblLoginMaster').DataTable({
"paging": true,
"lengthChange": false,
"searching": false,
"ordering": true,
"info": true,
"autoWidth": false,
"sDom": 'lfrtip'
});
}
}
});
}
This is my click event
$('tr.EditStyle').on('click', function () {
if ((this).val() != 0) {
var rowData = (this).children('td').val();
$('#id').val(rowData[0]);
$('#username').val(rowData[1]);
$('#emailId').val(rowData[2]);
$('#password').val(rowData[3]);
$('#role').val(rowData[4]);
}
});
I'm suspecting your click handler doesn't work as your rows do not exist by the time you attempt to listen for clicks. Try to change that, like this:
$('#tblLoginMaster').on('click', 'tr.EditStyle', function () {
...
});
If that solves your problem, you may check out oficial tutorial on that topic.
Another thing in your code that raises my concern is using jQuery $.ajax() method to populate your table and the very method you populate that:
in order to fetch your data dynamically, you should use DataTables ajax option and take the advantage of ajax.dataSrc:
$('#tblLoginMaster').DataTable({
...,
ajax: {
url: '/LoginMaster/GetLoginData',
method: 'GET',
dataSrc: //here goes json property or the method that retrieves table data out of json response
}
});
you don't need to cook up table body HTML on your own, you may simply point to corresponding source data properties within columns/columnDefs options, and make use of createdRow option to assign necessary row attributes:
$('#tblLoginMaster').DataTable({
...,
rowCreated: (tr, _, rowIdx) => $(tr).attr({
'class':'EditStyle',
'data-target': '#addUserModal',
'data-toggle': 'modal',
'value': rowIdx
}),
columns: [
{data: 'Id', header: 'Id'},
{data: 'Name', header: 'Name'},
{data: 'Password', header: 'Password'},
...
]
});
You may be reluctant to do such a global change to your app, but otherwise you may run into different sorts of issues related to AJAX-async nature and deprive yourself of the possibility to use the plethora of DataTables API methods to catch the bugs or enrich your app with new features.
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 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.
I'm working on a page that makes fairly heavy use of ajax. All the ajax forms appear to be working fine across browsers but one final step on the page is broken in IE8 and below.
Here is a demo page showing the problem: http://jolora.com/~fwm/
To reproduce the issue please fill in the final form (email name etc) - a list of markers will be shown on the map. The 'Request Appointment' button should fire an ajax function but instead it actually submits the form in IE7 and IE8 so it appears preventDefault isn't working.
Here's the relevant jQuery:
// Request appointment
$('#map').on('submit', 'form', function(event) {
event.preventDefault();
var solicitorID = $(this).attr('id');
solicitorRequest(solicitorID,applicationID);
});
function solicitorRequest(requestedSolicitor,currentApplication) {
$.ajax({
url: siteurl + 'wp-admin/admin-ajax.php',
data:{
'action':'do_ajax',
'fn':'request_solicitor',
'solicitor': requestedSolicitor,
'application': currentApplication
},
dataType: 'JSON',
success:function(data){
alert('Please check your email - this success function needs improving');
},
error: function(errorThrown){
alert('error');
//console.log(errorThrown);
}
});
}
The popups are built using Leaflet's bindPopup method http://leafletjs.com/reference.html#popup and here's the structure of the content I insert into the popup:
var popupContentBegin = '<form id="'
+ solicitor.id + '">'
+ '<h3>' + solicitor.name + '</h3>'
+ '<div class="contact-details">'
+ '<span class="addr">' + solicitor.address + '</span>';
var popupContentTel = '';
if(solicitor.telephone != false) {
popupContentTel = '<span class="tel">'
+ solicitor.telephone
+ '</span>';
}
var popupContentEnd = '</div>'
+ '<button type="submit">Request appointment</button>'
+ '</form>';
var popupContent = popupContentBegin + popupContentTel + popupContentEnd;
var marker = L.marker([lat, lng], {icon: solicitorIcon}).bindPopup(popupContent, popupOptions);
Any help would be greatly appreciated! Thanks.
Try changing your selector to:
$(document).on('submit', '#map form', function(event) {...
http://api.jquery.com/live/
EDIT: You need to call this function inside a ready function so that you can be sure the DOM was completely loaded:
$(function () {
// Put code here
});