i am trying to load data in datatable using ajax, this is my table definition:
<table id="appointments" class="display" width="100%">
<thead>
<tr>
<th>Activité</th>
<th>Pour le</th>
<th>Heure Début</th>
<th>Heure Fin</th>
<th>Référent</th>
<th>Etat</th>
<th>test</th>
<th>test2</th>
<th>test3</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
and this is the ajax call:
$("#appointments").dataTable({
"searching":false,
"ajax":function(data,callback,settings){
$.ajax({
url:"http://test.azprojet.fr/wsazprojet/api/entreprise/ManageAppointements",
datatype:"json",
type:"get",
data:{
domainName:$("[name='url']").val(),
IdUsager:$('input[name="IdUsager"]').val()
},
success:function(data,html,status){
},
error:function(html,status,error){
console.log("new error have occured")
console.log(error)
}
});}
});
when i apply this code , i get an empty dataTable containing the word "loading" ?
what 's wrong ?
update
it looks like that i missed calling callback(data) inside the success function , however after adding that i get this error :
Cannot read property 'length' of undefined
searching for solution i found that i need to set ajax.dataSrc inside the ajax object , but i didn't know how since i m calling a function here !
the problem is that , datatable accept this format of json data:
{
"data": [
{
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$320,800",
"start_date": "2011/04/25",
"office": "Edinburgh",
"extn": "5421"
}
]
}
so the solution was to add wrap my data like this :
data={"data":data}
Related
everything works fine. The only issue that i cannot fix/find is how to create a button and set the value of data: cvpdf inside a href of a button to open the cv
The cvpdf is the file name of a cv stored in the database.
<table id="dtBasicExample" class="table table-striped custom-table mb-0 datatable " >
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>surname</th>
<th>email</th>
<th>position</th>
<th>CV</th>
</tr>
</thead>
<tbody id="atn-tbody">
</tbody>
</table>
function showInformation(str) {
console.log(str);
$("#dtBasicExample").dataTable().fnDestroy();
$(document).ready(function(){
$("#dtBasicExample").dataTable({
scrollX: true,
"ajax":{
url: "data.php?q="+str ,
dataSrc:"",
},
"columns":[
{"data": "id"},
{"data": "name"},
{"data": "surname"},
{"data": "email"},
{"data": "position"},
{"data": "cvpdf"},
]
});
});
};
Let me help you out with this. you can apply this to any column data
columns: [
{
data: function(row){
return `Click This`
}
}
]
the "row" parameter will return the whole data for the current row, so you can access the object through the "row.your_key".
this is the best practice to make your code simpler.
the complete parameter can be accessed through This Link
Hope it can help!
I can't specify what/where is the problem, here is my code :
HTML :
<table id="companies" class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th class="center">
Id
</th>
<th>RegNo</th>
<th>Name</th>
<th class="hidden-480">Industry</th>
<th class="hidden-phone">
Size
</th>
<th class="hidden-480">LineOfDefence</th>
<th>Address</th>
</tr>
</thead>
</table>
Server side :
var result = new
{
rows = (from company in db.Company.ToList()
select new
{
id = company.CompanyId,
RegNo = company.RegestrationNumber,
Name = company.Name,
Industry = company.IndustryType.Name,
Size = company.CompanySize.Name,
LineOfDefence = company.LineOfDefence.Name,
Address = company.Address
}).ToArray()
};
return Json(result, JsonRequestBehavior.AllowGet);
and here is my Ajax Call :
<script>
$(document).ready(function ()
{
$('#companies').DataTable( {
"ajax": {
url: "/Company/GetCompanyGrid",
type: "GET",
dataType: "json"
}
});
});
</script>
I'm getting this error : "jquery.dataTables.min.js:181 Uncaught TypeError: Cannot read property 'length' of undefined"
note : I'm using jquery-1.12.3.js & DataTables 1.10.12.
Any help would be appreciated .
finally I've figured out the problem :
first : datatables expects specific format, so I changed my server side code like this :
var result = new
{
**draw = 1,
recordsTotal = db.Company.ToList().Count,
recordsFiltered = db.Company.ToList().Count,**
data = (from company in db.Company.ToList()
select new
{
Id = company.CompanyId,
RegNo = company.RegestrationNumber,
Name = company.Name,
Industry = company.IndustryType.Name,
Size = company.CompanySize.Name,
LineOfDefence = company.LineOfDefence.Name,
Address = company.Address,
}).ToArray()
};
return Json(result
, JsonRequestBehavior.AllowGet);
second : I've added these lines to my script
<script>
$(document).ready(function ()
{
$('#companies').DataTable( {
"ajax": {
url: "/Company/GetCompanyGrid",
type: "GET",
dataType: "json"
},"columns": [
{ "data": "Id" },
{ "data": "RegNo" },
{ "data": "Name" },
{ "data": "Industry" },
{ "data": "Size" },
{ "data": "LineOfDefence" },
{ "data": "Address" },
{ "data": "Logo" },
{ "data": null },
]
});
});
</script>
and now it's working perfectly.
Datatables expects the returned json to be in a specific format, as per the documentation - see the 'Returned data' section.
Your json should look something like this:
return Json(new
{
param.draw,
recordsTotal = result.Count,
recordsFiltered = result.Count,
data = result
}, JsonRequestBehavior.AllowGet);
The error is probably a result of datatables looking for a field that isn't present. Note that the draw value is sent in the original GetCompanyGrid() request, you don't need to generate it yourself.
How to put a 'if' query on Ignited datatable? Here is my query:
This is my controller:
function ajaxGetCard() {
$this->load->library('Datatables');
$this->datatables->set_database('retail');
$this->datatables
->select('studEmpID, fullname, serialNumber, balance, If(status = "0", "Enable", "Disabled") as status')
->from('retail_card');
echo $this->datatables->generate();
}
This is my view:
<script type="text/javascript">
$(function() {
$('#example').DataTable( {
"bProcessing": true,
"bserverSide": true,
"ajax": "<?php echo site_url('card/ajaxGetCard'); ?>",
"columns": [
{ "data": "studEmpID" },
{ "data": "fullname" },
{ "data": "serialNumber" },
{ "data": "balance" },
{ "data": "status" },
{ "data": "actions" }
]
} );
});
</script>
<table class="table table-bordered datatable table-striped" id="example">
<thead>
<tr>
<th>ID Number</th>
<th width="30%">Name</th>
<th>Serial</th>
<th>Balance (MYR)</th>
<th>Status</th>
<td>Actions</td>
</tr>
</thead>
When I run this, I've got this error:
DataTables warning: table id=example - Ajax error. For more information about this error, please see http://datatables.net/tn/7
I already refer the given url, but still not solve the problem. If I remove the the 'if' statement in that query, everything works fine. Please help
Recently, I got a requirement for an implementation of adding Child rows in a table. I have gone through the few APIs and found that datatables fits into my requirement. As of now I am implementing this web application in Springs and getting the data from the controller.
That is $resultSet.
Now this dynamic data I have to render in jsp page. Here I got stucked because I am not able to implement with datatable. I have seen the example of http://datatables.net/examples/api/row_details.html and tried removing Ajax data and used c:foreach loop in place it. But i didn't get any luck.
So can you guys please tell me how do I use datatables with the dyncamic data in order to display child rows.
My main concern is:
$(document).ready(function() {
var table = $('#example').DataTable( {
"ajax": "../ajax/data/objects.txt",
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "salary" }
],
"order": [[1, 'asc']]
} );
How do I represent the above block.
I tried with <table id="xx"> <c:foreach loop to iterate>
You can use data option to feed data into DataTables directly instead of using server-side script to return data via Ajax. This initialization option can be useful when creating a table from a JavaScript data source, or from a custom Ajax data get. However the data has to be of type Array.
I'm not familiar with Spring framework but I'm assuming you can produce a string with data in JSON format and output it in your page to assign to table_data_json. I'm using a sample JSON string var table_data_json = '[ /* skipped */ ]';.
/* Formatting function for row details - modify as you need */
function format ( d ) {
// `d` is the original data object for the row
return '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">'+
'<tr>'+
'<td>Full name:</td>'+
'<td>'+d.name+'</td>'+
'</tr>'+
'<tr>'+
'<td>Extension number:</td>'+
'<td>'+d.extn+'</td>'+
'</tr>'+
'<tr>'+
'<td>Extra info:</td>'+
'<td>And any further details here (images etc)...</td>'+
'</tr>'+
'</table>';
}
$(document).ready(function() {
var table_data_json = '[{"name":"Tiger Nixon","position":"System Architect","salary":"$320,800","start_date":"2011/04/25","office":"Edinburgh","extn":"5421"},{"name":"Garrett Winters","position":"Accountant","salary":"$170,750","start_date":"2011/07/25","office":"Tokyo","extn":"8422"},{"name":"Ashton Cox","position":"Junior Technical Author","salary":"$86,000","start_date":"2009/01/12","office":"San Francisco","extn":"1562"}]';
var table = $('#example').DataTable( {
"data": JSON.parse(table_data_json),
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "salary" }
],
"order": [[1, 'asc']]
} );
// Add event listener for opening and closing details
$('#example tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = table.row( tr );
if ( row.child.isShown() ) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
// Open this row
row.child( format(row.data()) ).show();
tr.addClass('shown');
}
} );
} );
td.details-control {
background: url('https://raw.githubusercontent.com/DataTables/DataTables/1.10.7/examples/resources/details_open.png') no-repeat center center;
cursor: pointer;
}
tr.shown td.details-control {
background: url('https://raw.githubusercontent.com/DataTables/DataTables/1.10.7/examples/resources/details_close.png') no-repeat center center;
}
<link href="//cdn.datatables.net/1.10.7/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="//cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>
<table id="example" class="display">
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th></th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Salary</th>
</tr>
</tfoot>
</table>
If I misunderstood your question, please let me know and I will update my answer.
I am using Ajax Datatable, I want to feed the table with Json data, which i am returning from MVC Action method. This is what i have tried so far,
My Controller action method
public ActionResult Index()
{
_dbcontext = new dbContext();
List<Employee> employees = new List<Employee>();
var query = (from e in _dbcontext.Employees select new { e.FirstName, e.LastName, e.Username, e.Password }).ToList();
return Json(query,JsonRequestBehavior.AllowGet);
}
And here is my Javascript on Index page
</script>
$(document).ready(function () {
$('#example').dataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "Home/Index",
"dataType": "jsonp"
}
});
});
</script>
But on page load only the plain Json data can be seen and no data table, I think It is not even rendering the Html on the index page and hence neither Datatable as I can not see anything in chrome debugger.
Also, Html and script referencing is all Ok as I can see the results when I feed the datatable from a .txt file having array of data.
I don't know what is the right way to do that, If somebody has the solution for that, then please help, Thanks.
I think what you need to do is simply the following
</script>
$(document).ready(function () {
$('#example').dataTable({
"ajax": "/Home/Index",
"columns": [
{ "data": "FirstName" },
{ "data": "LastName" },
{ "data": "Username" },
{ "data": "Password" },
]
});
});
</script>
No need for the processing and serverside and they are used when you have large data and would like to have paging and sorting done on the server side which is not the case in your code
One possible way is to define your "regular" table markup in a razor view/partial/ view - id your table, ie, id="DataTables-Employee". Your controller code looks just fine but with an ActionResult return a View with the model data. This let you control the data by using razor syntax in your view, which I have found much easier than complex JSON results. (Also, I like to use AutoMapper to project my model data to - give it a try!)
Note: this is only one of several ways to do this. Server-side processing helps when working with huge datasets, but give the client-side a try. I use ajax but flatten your model result. More likely than not you will need to define your columns and map them to your JSON. If you want to post your table results, add a form tag. I use ajax for this and serialize my form before sending. I hope this helps!
public ActionResult Index()
{
_dbcontext = new dbContext();
List<Employee> employees = new List<Employee>();
var query = (from e in _dbcontext.Employees
select new {e.FirstName, e.LastName, e.Username, e.Password};
//I would recommend using AutoMapper and project your model to this
return View(query.ToArray());
}
Say you are working with an Index view:
#model dynamic
... //typical HTML table
<table class="display compact table table-striped table-hover dataTables_sizing table-condensed" id="dataTables-Employee">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>User Name</th>
<th class="no-sort">Actions</th>
</tr>
</thead>
#foreach (var emp in Model)
{
<tr>
<td>#emp.FirstName</td>
<td>#emp.LastName</td>
<td>#UserName</td>
<td style="width: 100px;">
<i class="fa fa-search"></i>
#Ajax.ActionLink("View", "Index", new { id = #app.EmployeeId },
new AjaxOptions
{
dateTargetId = "resultSection",
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace
})
</td>
</tr>
}
</table>
//Know make it a DataTable
$('#dataTables-Employee').DataTable({
scrollY: '330px',
scrollCollapse: true,
paging: true,
scrollX: false,
"columnDefs": [{
"orderable": false,
"targets": 2
}, {
className: "dt-center",
"targets": [3]
}],
"aria": {
"sortAscending": ": activate to sort column ascending",
"sortDescending": ": activate to sort column descending"
},
"options": {
"emptyTable": "No records to display..."
}
});
Example of results with Bootstrap styles: