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 :)
Related
I am new in AJAX and API`s:
I have created API (that returns an array of Status Items)
1- Index.php have the below code for the datatable:
<table id="example1" class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th class="center">Code</th>
<th class="center">Description</th>
<th class="center">Status</th>
<th class="center">Edit</th>
<th class="center">Delete</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot class="table-condensed table-bordered">
<tr>
<th class="center">Code</th>
<th class="center">Description</th>
<th class="center">Status</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</tfoot>
</table>
The second file2.php includes the Javascript and Jquery and Ajax code:
I write the code below to get the Json from the api and fetch the rows into the above table:
var table = $("#example1 tbody");
$.ajax({
url: 'API_ReadAllSeed_Status.php',
method: "GET",
xhrFields: {
withCredentials: true
},
success: function (data) {
table.empty();
$.each(data.AllStatus, function () {
var Active_Status = "";
//the code below is to set a specific element depending on the result
if (this["STATUS_ACTIVE"] == 1)
{Active_Status = "<td><span class='label label-success'>Activated</span></td>";}
else
{Active_Status = "<td><span class='label label-danger'>Deactivated</span></td>"}
table.append("<tr><td>" + this["STATUS_CODE"] + "</td><td>" + this["STATUS_DESCRIPTION"] + "</td>" + Active_Status + "</td> <td><a href='' class='btn btn-app addeditdelete' value='" + this["STATUS_ID"] + "'><i class='fa fa-edit'></i> Edit </a></td> <td><a href='' class='btn btn-app addeditdelete' value='" + this["STATUS_ID"] + "'><i class='glyphicon glyphicon-trash'> </i> Delete</a></td> </tr>");
});
}
});
Result:
The Json fetch successfully as I want but as shown in the picture, the rows are not inserted in the main body rows of the data table since nothing is working inside.
My Question:
How I am able to load the Json data into the datatable and use all its features [search and pagination and rows per page].
Finally it works nowt but still have a question:
$('#STATUS_TABLE').DataTable({
"ajax": {
"url": "API_ReadAllSeed_Status.php",
"dataSrc": "AllStatus"
},
"columns": [
{ "data": "STATUS_CODE" },
{ "data": "STATUS_DESCRIPTION" },
{ "data": "STATUS_ALT_DESCRIPTION" },
{ "data": "STATUS_ACTIVE" }
]
});
Question:
How I can change the format of the rows and to set different labels of the Status example rows with value 1 = Active and 0 = Deactivate.
After many searches and after trying many codes I found the below solution:
{ "data" : "STATUS_ACTIVE",
render : function(data, type, row) {
if (data == 1)
{data = "<span class='label label-success'>Activated</span>";}
else
{data = "<span class='label label-danger'>Deactivated</span>";}
return data;
}
},
I need to set class on table on spesific tr on ajax proses. my html table like below
<table class="table table-striped table-borderless table-hover" id="tablePray">
<thead>
<tr>
<th style="width:20%;">Nama / Name</th>
<th style="width:45%;">Keterangan / Description</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
foreach ($prays as $row)
{
?>
<tr id="prayRow<?php echo $row->id;?> ">
<td class="user-avatar"> <img src="<?php echo base_url();?>assets/admin/img/avatar.gif" alt="Avatar"><?php echo $row->name;?></td>
<td><?php echo $row->prayNeed;?></td>
<td class="text-right"> Healed</td>
</tr>
<?php
}
?>
and my jquery like this :
$('#changeStatusFrm').submit(function(e) {
e.preventDefault();
$id=$('#idPray').val();
$token=$('#token').val();
data = new FormData();
data.append("idPray",$id);
data.append("<?php echo $this->security->get_csrf_token_name();?>", $token );
$.ajax({
data: data,
type: "POST",
url: '<?php
echo base_url('Pray/ChangeStatus');
?>'
,
cache: false,
contentType: false,
processData: false,
success: function(url) {
var result=url.split('|');
$('#token').val(result[0]);
alert('Pray status have been change');
$("#mod-danger").modal("hide");
$("#tablePray tr#prayRow"+$id).addClass('table-success');
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
});
I want to change the spesific tr if row link get click.
Can anybody help me?? thx
If you are using datatable then you can use something like this :
$('#tablePray').dataTable( {
"columnDefs": [
{ className: "my_class", "targets": [ 0 ] }
]
} );
reference link :- https://datatables.net/reference/option/columns.className
This example here demonstrates adding and removing classes on a row from a click event.
Set like this
var val = "#prayRow"+$id;
$(val).addClass('table-success');
Make sure #prayRow$id is already defined in table
FYI: move alert('Pray status have been change'); to end of the line
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
Im having troubles with showing the data that i want in the tables. I did the following sketch so you guys can figure out what i want to display:
The query i have in my php/mysql connector brings me each "Tarea" data(second table) with "proyecto" and "alerta" but i need to display "proyecto" and "alerta" only 1 time per row.
So i did this in angular to storage the data of the second table(Tarea, Termino, Estado, Nombre), while i display the data of the first table.
scope.llamada1 = function() {
$http.get("conector.php?tipoDato=query1")
.then(function(response) {
$scope.mensajeEspera = "";
$scope.datos1 = response.data;
for(var i = 0; i < $scope.datos1.length; i++){
var currentObj = $scope.datos1[i];
$scope.datos1[i].detalleProyecto = [{
"tarea":currentObj.tarea ,
"fecha_termino":currentObj.fecha_termino ,
"estado":currentObj.estado,
"nombre_completo":currentObj.nombre_completo}];
}
});
}
And in the html i get the data like this, with the table inside the last :
<table id="tablaTareas" class="table table-striped table-bordered" >
<thead>
<tr>
<td><b>Proyecto</b></td>
<td><b>Alerta</b></td>
<td><b>Tareas</b></td>
</tr>
</thead>
<tbody>
<tr ng-repeat="x in datos1 ">
<td style="vertical-align: top;">{{x.proyecto}}</td>
<td style="vertical-align: top;">{{x.alerta}}</td>
<td style="vertical-align: top;">
<table class="table table-striped table-bordered" >
<thead>
<tr>
<td><b>Tarea</b></td>
<td><b>Termino</b></td>
<td><b>Estado</b></td>
<td><b>Responsable</b></td>
</tr>
</thead>
<tbody>
<tr ng-repeat="y in x.detalleProyecto track by $index">
<td>{{y.tarea}}</td>
<td>{{y.fecha_termino}}</td>
<td>{{y.estado}}</td>
<td>{{y.nombre_completo}}</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
But is repeating "Proyectos" and "Alerta" and displaying 1 "Tarea" per row and not every task together per proyect and alert, an example below.
you should try to arrange your data this way
[
{
name: nombre_completo,
data: [
{
tarea,
fecha_termino,
estado
}
]
}
]
where name is the repeated data that you don't want to repeat
a little example
if you have data like
[{country: Chile, name: Martin},{country: Chile, name: Nico},{country: Peru, name: Seba},{country: Peru, name: Nicole},{country: Argentina, name: Warencita}]
try this (assuming var datos is where your data is stored)
var datos = [{country: 'Chile', name: 'Martin'},{country: 'Chile', name: 'Nico'},{country: 'Peru', name: 'Seba'},{country: 'Peru', name: 'Nicole'},{country: 'Argentina', name: 'Warencita'}]
var temp = []
var exists
var place
for(var i = 0; i < datos.length; i++){
exists = false;
for(var k = 0; k < temp.length; k++){
if(datos[i].country === temp[k].country){
exists = true;
place = k;
break;
}
}
if(exists){
temp[place].data.push({
name: datos[i].name
})
}else{
temp.push({
country: datos[i].country,
data: [{
name: datos[i].name
}]
})
}
}
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