I am trying to make ajax based search but i am very new in javascript and ajax. I need sorting, filtering etc. for results so i put results into Datatables.
First of all i'am using standard html form input (it is main search field):
<input type="text" class="form-control" formmethod="post" oninput="return delayExecute();" id="name" name="name" size="61" autofocus/>
It calls delayExecute() function when user put something into form. Next, one second after user is finished writing the script run ajax request. Script looks like that:
<script>
var typingTimer;
var doneTypingInterval = 700;
function delayExecute()
{
clearTimeout(typingTimer);
typingTimer = setTimeout(
function(){makeAjaxRequest(name)},
1000
);
return true;
}
function makeAjaxRequest(name) {
$('#loading')
.show()
var myrequest = $.ajax({
url: 'ajax_search',
type: 'post',
data: {name: $('input#name').val()},
ajaxSend: function() {
},
success: function(response) {
$('table#dataTables-example tbody').html(response);
},
complete:function(){
//
$('#loading')
.hide();
$('#dataTables-example').dataTable({
// "destroy": true,
"processing": true,
"aaSorting": [],
"iDisplayLength": 10,
"aLengthMenu":[[10, 15, 25, 35, 50, 100, -1], [10, 15, 25, 35, 50, 100, "All"]]
}).columnFilter(
{
aoColumns: [
{type: "null"},
{sSelector: "#mag_filter_column", type: "select"},
]
}
);
}
});
};
In Php file (ajax_request) i read data from data base. Next I use echo function to put things into table like that:
echo '<tr>';
echo '<td>'.$some_variable.'</td>';
echo '<td>'.$other_variable.'</td>';
echo '</tr>;
And table in the view looks like that:
<table class="main-search table table-striped table-bordered table-hover" id="dataTables-example">
<thead>
<tr>
<th>Col</th>
<th>War</th>
<th>Symbol</th>
<th>Name</th>
<th>Quantity</th>
<th>Descripion</th>
<th>Photo</th>
</tr>
</thead>
<tfoot>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tfoot>
<tbody>
</tbody>
</table>
This whole thing almost work. When i make search for the first time it loads everything into datatable and everything works good (pagination, sorting etc). But when i do second search (change some word for example) - ajax serch runs, it find something but the data doesn't load into datatable. I think that i need to find way to refresh datatable plugin. I tried to use datatable.clear(), datatable.destroy() and couple other things but nothing works well for me. What is the right way to do it?
My datatable plugin version: DataTables 1.10.5
jquery version: 2.1.1
Related
I'm new in Jquery and I want once the user adds new row and give the important information once he clicks on "Ajouter" button it will add on data base then reload the table automatically.
Once i run that I found that the data added successfully to the database however "tablebqup" does not reload anymore and it I found this error :
Uncaught TypeError: Cannot set property '_DT_CellIndex' of undefined
Here is the function to add the new element:
$("#newbq").click(function () {
var indexadd= $('table#tablebqup tr:last').index() + 1;
//Now add this row to the table:
var row='<tr><td></td><td contenteditable="true"></td><td contenteditable="true"></td><td contenteditable="true"></td><td contenteditable="true"></td><td contenteditable="true"></td><td colspan="2"> <button id="add'+indexadd+'" class="btn btn-info addbc" name="button">Ajouter</button> </td></tr>';
$('#tablebqup').append(row);
$(".addbc").click(function () {
var nombc=($(this).parent().parent().find('td:eq(1)').html());
var abrv= ($(this).parent().parent().find('td:eq(2)').html());
var sigsoc=($(this).parent().parent().find('td:eq(3)').html());
var telf=($(this).parent().parent().find('td:eq(4)').html());
var fx=($(this).parent().parent().find('td:eq(5)').html());
// if (nombc=="" || abrv=="" || sigsoc=="" || (telf=="" && fx==""))
if (nombc=="")
{
alert("Rempier toutes les informations de la banque d'abord")
}
else {
$choix=confirm("voulez vous vraiment ajouter la banque");
if ($choix)
{
console.log(nombc);
$.post(basUrl+'views/component/updtbq.php',
{
action:'add_bq',
nomb:nombc,
abrvb:abrv,
sigsocial:sigsoc,
tel:telf,
fax:fx,
}, function(data) {
alert(data);
$('#tablebqup').DataTable().ajax.reload();//My problem is here
});
}
}
});
});
In the fist time one i run it it showed something like this :
“Uncaught TypeError: $(…).DataTable is not a function”
To solve it i added the appropriate link and script:
Doing that the error has changed to :
Uncaught TypeError: Cannot set property '_DT_CellIndex' of undefined
What surprised me that i have used above similar logic I mean use the same:
$('#tablebqup').DataTable().ajax.reload();
and once I click another button just to modify information on data base in this way :
$(".modif").click(function () {
$choix=confirm("voulez vous vraiment sauvegarder les modifications");
if ($choix)
{
var id=($(this).parent().parent().find('td:eq(0)').html());// the value in the 1st column.
var nombc=($(this).parent().parent().find('td:eq(1)').html());
var abrv= ($(this).parent().parent().find('td:eq(2)').html());
var sigsoc=($(this).parent().parent().find('td:eq(3)').html());
var telf=($(this).parent().parent().find('td:eq(4)').html());
var fx=($(this).parent().parent().find('td:eq(5)').html());
console.log(id);
$.post(basUrl+'views/component/updtbq.php',
{
action:'update_bq',
idbc:id,
nomb:nombc,
abrvb:abrv,
sigsocial:sigsoc,
tel:telf,
fax:fx,
}, function(data) {
$('#tablebqup').DataTable().ajax.reload();
});
}
That work perfectly without adding any of this two links!!!
Here is the dtail of the error:
Uncaught TypeError: Cannot set property '_DT_CellIndex' of undefined
at Ga (datatables.min.js:36)
at M (datatables.min.js:28)
at HTMLTableRowElement.<anonymous> (datatables.min.js:28)
at jquery-3.2.1.min.js:2
at Function.map (jquery-3.2.1.min.js:2)
at r.fn.init.map (jquery-3.2.1.min.js:2)
at ma (datatables.min.js:28)
at e (datatables.min.js:104)
at HTMLTableElement.<anonymous> (datatables.min.js:104)
at Function.each (jquery-3.2.1.min.js:2)
Here is my php file:
function add_bq()
{
if((isset($_POST['nomb']))
&&(isset($_POST['abrvb']))
&&(isset($_POST['sigsocial']))
&&(isset($_POST['tel']))
&&(isset($_POST['fax']))
){
$nomb=trim($_POST['nomb']);
$abrv=trim($_POST['abrvb']);
$sigc=trim($_POST['sigsocial']);
$tel=trim($_POST['tel']);
$fax=trim($_POST['fax']);
//Update les banques
MainController::addBanque($nomb,$abrv,$sigc,$tel,$fax);
include 'C:/wamp/www/Mini_Prj/views/component/tbbanqueupd.php';
}
and here is the included:"tbbanqueupd.php":
<?php
require_once("C:/wamp/www/Mini_Prj/controllers/mainController.php");
$bnqs=MainController::getBanque();
echo'
<div>
<h3> Mise a jours des banques</h3>
<div >
<div class="table-responsive">
<table id="tablebqup" class="tableau table table-fixed table-bordered table-dark table-hover ">
<thead>
<tr>
<th>Id Banque</th>
<th>Nom de la banque</th>
<th>Abrev </th>
<th>Siège Sociale</th>
<th>Tel</th>
<th>Fax</th>
<th>Modifier</th>
<th>Supprimer</th>
</tr>
</thead>
<tbody>
<form method="post">
';
$i=0;
foreach ($bnqs as $bnq) {
echo
" <tr>
<td>".$bnq['idbc']."</td>
<td contenteditable='true'>".$bnq['nomb']."</td>
<td contenteditable='true'>".$bnq['abrvb']."</td>
<td contenteditable='true'>".$bnq['sigsocial']."</td>
<td contenteditable='true'>".$bnq['tel']."</td>
<td contenteditable='true'>".$bnq['fax']."</td>
<td> <button id='modif$i' class='btn btn-info modif' name='button'>Modifier</button> </td>
<td> <button id='supp$i' class='btn btn-info supp' name='button' onclick='suprimer(this.id)'>Supprimer</button> </td>
</tr>";
$i++;
}
echo'
</form>
</tbody>
</table>
</div>
<button type="button" class="btn btn-info" name="button" id="newbq" >Nouvelle banque</button>
</div>
</div>';
I thought that maybe the problem is because i allow the user to not filling all the informations, but i want that it gonna be in this way the user enters just the important field.
How could I solve this problem?Can someone help.
It gives me this error when the number of td doesnt match the number of th, or when I use colspan...
Depending on your css, it could be hard to see. I'd add a border to the table while testing it out...
A simple mistake, the table header had a column " with no title, but the column did not exist in the table itself. I could not see it missing (because o no title and no borders).
Was helped by looking at the line in the datatable.js which gave the error - was implying a tr was at fault, so looked more carefully at my table and not my overall code
From your code, I don't see the DataTabe initialization, usually placed inside the Document Ready function. So:
Try to Initialize your table with an explicit configuration for each column ("visible:true" is a dummy setting that just confirms it is visible)
Add the "datatable" class to your table html. Example:
Example:
$(document).ready(function () {
var myTable= $('#tablebqup').DataTable({
columns:[
//"dummy" configuration
{ visible: true }, //col 1
{ visible: true }, //col 2
{ visible: true }, //col 3
{ visible: true }, //col 4
{ visible: true }, //col 5
{ visible: true }, //col 6
{ visible: true }, //col 7
{ visible: true } //col 8
]
});
});
And on the html:
<table id="tablebqup" class="tableau table datatable table-fixed table-bordered table-dark table-hover ">
Explanation:
The "DataTable" initialization method should have the same number of columns on its configuration as the number of <th>'s/<td>'s on your html.
Wrong example:
//Javascript Code
var myTable= $('#myTableId').DataTable({
columns: [
//any column configuration
{ "bSearchable": false }, //col 1
{ "bSearchable": true }, //col 2
{ "bSearchable": true }, //col 3
{ "bSearchable": false }, //col 4
{ "bSearchable": false }, //col 5
{ "bSearchable": false } //col 6
]
});
And the html markup:
<table id="myTable" class="table datatable">
<thead>
<tr>
<th>col 1 header</th>
<th>col 2 header</th>
<th>col 3 header</th>
<th>col 4 header</th>
</tr>
</thead>
<tbody>
<tr>
<td> data col 1, row 1</td>
<td> data col 2, row 1</td>
<td> data col 3, row 1</td>
<td> data col 4, row 1</td>
</tr>
</tbody>
</table>
So even if the number of <td>'s and <tr>'s are matching on the html, having more columns configured on the DataTable method will cause this exception to be thrown. In this example, removing the configuration lines for col 5 and col 6 from the DataTable method would fix the error.
I had correct number of columns in thead-th section and tbody-td section. There was no colspan added on any th or td elements but I was getting the same issue. I did some more research and found that I disabled sorting feature on a column number which was not exist in my data table.
Actually I had only 4 columns in my data table while I was trying to disable sorting feature for 6th number column. It was an accident. I forgot to change it. Code was as:
$(document).ready(function()
{
$('#datatable').DataTable( {
"aoColumnDefs": [
{ 'bSortable': false, 'aTargets': [0,1,6] }
],
responsive: true,
});
});
Then I changed 'aTargets' value, which could be set upto 3 as per my case and correct code was as:
$(document).ready(function()
{
$('#datatable').DataTable( {
"aoColumnDefs": [
{ 'bSortable': false, 'aTargets': [0,1,3] }
],
responsive: true,
});
});
It worked for me. Happy to share and help others :)
I'm going straight to the point here.
what I am trying to accomplish is to populate the table using ajax.
this gives me jquery.dataTables.min.js:39 Uncaught TypeError: Cannot read property 'length' of undefined error.
here's my code:
my php code:
public function pending_data(){
$result = $this->ticketing_m->get_pending_tickets();
echo json_encode($result);
}
JQUERY
var datatable = $("#datatable");
datatable.DataTable({
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": datatable.data('url')
});
HTML
<table id="datatable" class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%" data-url="<?php echo site_url(array("dashboard","pending_data")); ?>">
<thead>
<tr>
<th>Ticket Number</th>
<th>Subject</th>
<th>From</th>
<th>Date Created</th>
</tr>
</thead>
</table>
QUERY RESULT
First off, you should probably set bServerSide to false. If it is true you need to actually read the request parameters, do server side processing and structure your return data as outlined in the Server-side processing documentation. Since you are doing none of those things here I'm assuming you simply want to use Ajax sourced data and let the DataTables javascript handle the table processing
Next, structure your json with the table data inside data as shown here in example #2. Your json should look something like this:
{
"data": [
{
"date_created": "2017-06-13 13:57:24",
"full_name": "John Doe",
"subject": "Test",
"ticket_number": "Ticket 1234"
},
...
]
}
To accomplish this you might do something as simple as this in the response from pending_data():
echo json_encode(array('data' => $result));
Also, the way you have your DataTables properties set up here looks like you are either using a very old version or an outdated syntax. I'd suggest installing the latest version and using up to date code. You can get all the downloads and examples you might need at: https://datatables.net
I think your ajax source has 4 columns.
But you have 5 columns in < thead >.
Pls remove one tag in < thead >.
<table id="datatable" class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%" data-url="<?php echo site_url(array("dashboard","pending_data")); ?>">
<thead>
<tr>
<th>Ticket Number</th>
<th>Subject</th>
<th>From</th>
<th>Date Created</th>
</tr>
</thead>
</table>
var oTable = $('#datatable').dataTable({
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "${pageContext.request.contextPath}/",
"aoColumns" : [
{ "mData": "Ticket Numbe" },
{ "mData": "Subject" },
{ "mData": "From" },
{ "mData": "Date Created" }
]
});
I don't get the exact problem.This may help..
Do something like that also use data type https://datatables.net/examples/server_side/jsonp.html
"processing": true,
"serverSide": true,
"ajax": {
"url": "scripts/jsonp.php",
"dataType": "jsonp"
}
Use it like:
var url = 'http://www.json-generator.com/api/json/get/cbEfqLwFaq?indent=2';
var table = $('#example').DataTable({
'processing': true,
'serverSide': true,
'ajax': {
type: 'POST',
'url': url,
'data': function (d) {
console.log(d.order);
return JSON.stringify( d );
}
}
});
Working Fiddle
I am using jquery datatable use it from external cdn
<script src="http://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
and my table is
<table class="table table-bordered data-table" id="blocked_list">
<thead>
<tr>
<th>User Name</th>
<th>Email</th>
<th>Action</th>
</tr>
</thead>
</table>
and cal this in jquery function
#section('script')
<script>
$('#blocked_list').DataTable({
"ajax": "{{ route('user.sold_products') }}",
"columns": [
{ data: 'id' },
{ data: 'buyer_id'},
{ data: 'seller_id' },
]
});
</script>
#endsection
here i think i done correctly but the data not displayed inside my table and i call data from my controller is:
public function all(){
$user = Auth::user();
$block = Block::all();
$bl = Block::where('buyer_id',$user->id)->get();
return Response::json([
'data' => $block
], 200);
}
my controler having following values inside data variable
{"data":[{"id":1,"seller_id":12,"buyer_id":11,"email":"","created_at":"2017-06-01 11:37:54","updated_at":"2017-06-01 11:37:54"},{"id":2,"seller_id":10,"buyer_id":11,"email":"","created_at":"2017-06-01 14:20:51","updated_at":"2017-06-01 14:20:51"}]}
when thevalues not displayed inside myy laravel table i doknow why can anyone please help to solve this issue.
I have a table in a page for example:-
<tr>
<th>no</th>
<th>name</th>
<th>age</th>
<th>actions</th>
</tr>
<tr>
<td>$i</td>
<td>$name</td>
<td>$age</td>
<td>Delete</td>
</tr>
on the click of the delete it will go the controller through jquery and successfully delete the row, after that I want to show the updated table means without that deleted row. for this now I'm using another page and with the table data, on success I'm doing like this:
$(.updated_table_view).html(data.view);
is there any other simple way to do this like without an another page?
Presumably "...will go the controller through jquery..." means via Ajax, so if you want it to just do a simple removal, just hide the row:
jsFiddle: https://jsfiddle.net/842x2wuc/
<script>
$(document).ready(function(){
$('.delete').click(function(e) {
e.preventDefault();
var thisBtn = $(this);
$.ajax({
url: '/link/to/delete.php',
type: 'post',
data: { id: thisBtn.attr('href') },
success: function(response) {
// This will fade out the row
thisBtn.closest('tr').fadeOut('fast');
}
});
});
});
</script>
First I'll mention what I am trying to achieve. I am using CodeIgniter framework of PHP. I have 5 tables in my database and I want to display them in Datatables format on a button click on the display page. I am using server side processing php as data source. So at first I made the code for displaying only one table in Datatable format and was successful in it. Now I want to display one table at a time out of 5 on button click event. But $aColumns length should be equal to number of columns defined in HTML table. Now considering marks tabe, it has 4 columns student_id, exam_id, subject_id and marks_achieved. Now another table is branch and has 2 columns only branch_id and branch_name. So I cannot increase or decrease tags in HTML dynamically so I am confused.
Also I am using this source to create datatables.
You can check my getTable() function here.
jQuery:
$(document).ready(function()
{
$('#datatable').dataTable({
"sPaginationType":"full_numbers",
"bJQueryUI":true,
"bProcessing": true,
"bServerSide": true,
"sServerMethod": "GET",
"sAjaxSource": "datatable/getTable",
"iDisplayStart": 0,
"iDisplayLength": 10,
"aLengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
"aaSorting": [[0, 'asc']],
"aoColumns": [
{ "bVisible": true, "bSearchable": true, "bSortable": true },
{ "bVisible": true, "bSearchable": true, "bSortable": true },
{ "bVisible": true, "bSearchable": true, "bSortable": true },
{ "bVisible": true, "bSearchable": true, "bSortable": true }
]
})
$('input[type=button]').bind('click', function(){
var param = $(this).attr('id');
data = param + '=1';
$.ajax({
type: 'POST',
url: 'datatable',
data: data
}).done(function( data ) {
console.log(data);
$('#display_area').html(data);
});
})
});
HTML:
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript" src="../js/javascript.js"></script>
<script type="text/javascript" src="../js/jquery.dataTables.min.js"></script>
</head>
<body id="dt_example">
<form action="" method="post">
<input type="button" id="display_branch" name="display_branch" value="Display Branch Table" >
<input type="button" id="display_marks" name="display_marks" value="Display Marks Table" >
</form>
<div id="container">
<div id="demo">
<table id="datatable" cellpadding="0" cellspacing="0" border="0" width="100%">
<thead>
<tr>
<th>Student ID</th>
<th>Exam ID</th>
<th>Subject ID</th>
<th>Marks Achieved</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
<tfoot></tfoot>
</table>
</div>
<div class="spacer"></div>
</div>
</body>
</html>
To get the columns dynamically I have made this change as shown below in datatable.php but it is not working. What is wrong here or I should try some other approach ?
if(isset($_POST['display_marks']))
{
$aColumns = array('student_id', 'exam_id', 'subject_id', 'marks_achieved');
$sTable = 'marks';
}
if(isset($_POST['display_branch']))
{
$aColumns = array('branch_id', 'branch_name');
$sTable = 'branch';
}
EDIT:
The solution posted by user1190992 works but the whole approach is changed. And in that I want to sanitize the headers of the columns. "branch_id" is displayed instead I want to display Branch ID. How can I perform this sanitization ?
This is a very simple way for creating HTML from JSON data dynamically. It doesn't use server side processing though.
JavaScript
$(document).ready(function() {
$(".abutton").click(function() {
$('#myDatatable_wrapper').detach(); //Remove existing table
var table = '<table id="myDatatable" class="table"><thead><tr>';
$.ajax({
url: 'dt.php',
data: "table_id="+$(this).attr("id"),
type: "POST",
success: function (data) {
$.each(data.aoColumns, function(key, value) {
table += "<th>"+value+"</th>";
});
table += "</tr></thead><tbody>";
$.each(data.aaData, function(key, row) {
table += "<tr>";
$.each(row, function(key, fieldValue) {
table += "<td>"+fieldValue+"</td>";
});
table += "</tr>";
});
table += '<tbody></table>';
$('.container').html(table);
$('#myDatatable').dataTable();
},
dataType: "json"
});
});
});
PHP
$table_id = filter_input(INPUT_POST, "table_id", FILTER_SANITIZE_STRING);
$dbconn = mysqli_connect("localhost", "username", "password");
if($table_id == "table1") {
$sql_query = mysqli_query($dbconn, 'SELECT * FROM display_branch');
}
else {
$sql_query = mysqli_query($dbconn, 'SELECT * FROM display_marks');
}
if(mysqli_num_rows($sql_query) == 0) {
echo "Check your ID";
exit(1);
}
$data = array();
$data['aaData'] = array();
while($row = mysqli_fetch_assoc($sql_query)) {
$data['aaData'][] = $row;
}
$data['aoColumns'] = array();
while($finfo = mysqli_fetch_field($sql_query)) {
$data['aoColumns'][] = $finfo->name;
}
echo json_encode($data);
HTML
<button id="table1" class="abutton">Table 1</button><br /><button id="table2" class="abutton">Table 2</button>
<div class="container"></div>
Hope this helps.