I want to create jquery Datatables onclick of button a function will be called and inside function ajax will get data from database. I am passing certain data to server on click via url parameter.
Below is my ajax call on button click.
$(document).ready(function() {
$('#example').DataTable();
}
function loadData() {
var strUrl = "batch.jsp?patientname=" + patientname
+ "&dobstart=" + dobstart + "&dobend=" + dobend
+ "&startage=" + startage + "&endage=" + endage
+ "&location=" + location + "&account="
+ account;
$.ajax({
url : strUrl,
type : "POST",
dataType: 'json',
success : function(data) {
formdata += "<table id='patientdata' class='display' cellspacing='0' width='100%'>"
+"<thead>"
+"<tr>"
+"<th>ID</th>"
+"<th>Name</th>"
+"<th>Date of Birth</th>"
+"<th>Location</th>"
+"<th>Email Address</th>"
+"</tr>"
+"</thead>"
+"<tbody>";
$.each(data.patientdata, function(index, item) {
formdata += "<tr>"
+"<td>"+item.uid+"</td>"
+"<td>"+item.name+"</td>"
+"<td>"+item.dob+"</td>"
+"<td>"+item.location+"</td>"
+"<td>"+item.email+"</td>"
+"</tr>";
});
formdata += "</tbody></table>";
$("#ptdata").html(formdata); // div in html
$('#exampledata').dataTable();
},
error : function(thrownError) {
alert("Error in ajax post call "+thrownError);
}
}); }
I found one code but here server is called on load in document ready but I want to call it during onclick of button.
Below code which makes a call to server on load
// POST data to server
$(document).ready( function() {
$('#example').dataTable( {
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "xhr.php",
"fnServerData": function ( sSource, aoData, fnCallback, oSettings ) {
oSettings.jqXHR = $.ajax( {
"dataType": 'json',
"type": "POST",
"url": sSource,
"data": aoData,
"success": fnCallback
} );
}
} );
} );
$('#example').DataTable();code in loadData function after$("</tbody></table>").appendTo("#ptdata");this line.$('#example').DataTable();but since this is a dynamic table it hasn't been created yet therefore there is nothing to initialize.$('#example').DataTable()in my onclick button function after table creation as you told and it worked for me. But there are few things which I need to do, like pagination I will do that. Thank You