Control error: Invalid JSON response. In dataTables - javascript

I am working with dataTables to represent my data, and also adds a select field in which, through a query, I load the dataTable again according to the city chosen in my select field, the problem is when I do not have any records of the selected city , And the dataTables sends me the error: Invalid JSON response, how can I control this?
I leave my script and part of my html
//My field select
<div class="col-lg-3">
<select class="form-control" name="city">
<option>Filter by city...</option>
<?php
foreach ($arrayCity as $id => $name)
echo '<option value="',$id,'">'.$name.'</option>';
?>
</select>
</div>
//My table where I uploaded the data
<table class="table " id="table" width="100%">
<thead class="thead-inverse">
<tr>
<th>ID</th>
<th>name</th>
<th>email</th>
<th>city</th>
</tr>
</thead>
</table>
$(document).ready(function(){
var getUser;
//Start datatable when loading document.
getUser = $("#table").DataTable({
'ajax': baseurl+'User/getUser',
'orders': [],
responsive: true
});
//Function that destroys the dataTable event.
function destroy_data_table(){
getUser = $("#table").dataTable();
if (getUser != undefined){
getUser.fnDestroy();
}
}
//Select event change to call function
$('select[name=city]').change(function(){
destroy_data_table();
var id = $('select[name=city]').val();
filterCity(id);
});
//Function that reloads the datatable and filters the search by city.
function filterCity(id){
getUser = $("#table").DataTable({
'ajax': baseurl+'City/getCity/'+id,
'orders': [],
responsive: true
});
}
});

Related

jQuery Datatables Reload

I'm facing an issue using the Datatables plug-in regarding a table reload after the user adds a row.
I'm receiving some JSON data as part of a webservice call, after successfully receiving that data, I am calling a function that will build the table rows and append them to the tbody of the datatable as follows:
const buildTableRows = obj => {
const table = document.querySelector('#participantes tbody');
table.innerHTML = "";
for (item of obj) {
const tableRow = `<tr id="${item.ContactoId}" data-contributos="${item.Contributos}" data-updated="false" class="participante-row"><td><i class="material-icons">arrow_right</i>${item.Nome}</td><td class="contributos"><input value="${item.Contributos}">&nbsp&nbsp&nbsp<i class="material-icons delete">delete_forever</i></td></tr>`;
table.insertAdjacentHTML('beforeend', tableRow);
}
}
After this, I call another function responsible for initializing the Datatable and saving it to a global object for future reference:
const buildDataTable = () => {
const table = $('#participantes').DataTable({
"pagingType": "simple_numbers",
"pageLength": 4,
"lengthChange": false,
"columnDefs": [{
"targets": 1,
"orderable": false
}],
responsive: true
});
controlObj.datatable = table;
}
In my HTML I have a dynamically generated select element which lets the user add a row to the table. When the user adds the row, those two functions get called again. I can see the new row in my data structure but the table doesn't get refreshed without a page reload. I went through the plugin docs and tried to use the destroy method, rows.add(), clear(), draw() etc.. but nothing seems to work for me. The table structure is already in the DOM, I just need to reload the table. Any help would be much appreciated
Datatable cannot be clear and redraw for updated HTML DOM for table but it has to be inserted using JSON array.
To refresh it after change in DOM, you need to destroy the table and re-initalize it.
See below example where on click of ADD button I have added new row and reiniitalized the table but before that I have destroyed it.
$(document).ready(function() {
//Initialize the table and save it in a variable.
var table = $('#example').DataTable();
var id = 0;
$('#add').on('click', function(){
table.destroy();
//add row to the table
var html = '<tr><td>' + id + '</td><td>First Name' + id + '</td><td>Last Name' + id + '</td></tr>';
//console.log(html);
$('#example tbody').append(html);
id++;
table = $('#example').DataTable();
});
} );
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/dataTables.jqueryui.min.css">
<script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script type="text/javascript" language="javascript" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<table id="example" class="display nowrap" style="width:100%">
<thead>
<tr>
<th>ID</th>
<th>First name</th>
<th>Last name</th>
</tr>
</thead>
<tbody>
<tr>
<td>00</td>
<td>First</td>
<td>Last</td>
</tr>
</tbody>
</table>
Click Button to Add row : <input id="add" value=" ADD " type="button">
Yes you can use DataTable api. without destroying table you just need a function.
$(document).ready(function() {
var dt = $('#example').DataTable();
$('#addRow').click(function () {
var rowHtml = $("#newRow").find("tr")[0].outerHTML
console.log(rowHtml);
dt.row.add($(rowHtml)).draw();
});
});
here is working example

How can I get the value of a cell in the table to pass to a variable in PHP?

I'm a little frustrated because I can not get the value of the cell and save it in a php variable so I can then query the database.
<div class='card-body'>
<div class='table-responsive'>
<table class='table table-bordered' id='dataTable' width='100%'
cellspacing='0'>
<thead>
<tr>
<th>Host Name</th>
<th>Time</th>
<th>Cpu</th>
<th>Mem</th>
<th>Load</th>
<th>Disk</th>
</tr>
</thead>
<tbody>
<?php
foreach ($results['results'][0]['series'] as $array) {
echo '<tr>';
echo "<td>{$array['tags']['hostname']}</td>";
foreach ($array['values'][0] as $value) {
echo "<td>{$value}</td>";
}
echo '</tr>';
}
?>
</tbody>
</table>
</div>
</div>
The above code produces a table with elements.
I wanted to get the name of the host when I clicked on a row and save a variable in php to be able to query a database.
https://i.imgur.com/fI7Td5L.png
Summary:
I would like to be able to click on a hostname and save that value in a PHP variable to be able to use a database query in a WHERE clause, for example SELECT CPU, MEMORY FROM DATA WHERE HOSTNAME = VARIABLE_HOSTNAME.
VARIABLE_HOSTNAME would have the value of the row that you select.
Thank you very much everyone for your time and help.
On the higher-level, you can use AJAX for this problem.
Example steps:
add the hostname value as an attribute in the tr tag
add an event(click) for each row in the table. when clicked, get the attribute from the selected table row then use an AJAX to pass this value to the PHP.
use the passed hostname value in your DB query on the PHP
Example Code:
<table>
<tr data-hostname-value="Hostname value 1" onclick="saveHostname()">
<td>Hostname value 1</td>
</tr>
<tr data-hostname-value="Hostname value 2" onclick="saveHostname()">
<td>Hostname value 2</td>
</tr>
</table>
<script>
function saveHostname() {
$('tr').on('click', function() {
var hostnameVal = $(this).attr('data-hostname-value');
$.ajax({
method: "POST",
data: "&hostname=" + hostnameVal,
url: PHP_URL,
success: function(data) {
// success JS code.
}
});
})
}
</script>
hope this helps, thanks.

How to get value from html select tag option value using onChange event using jQuery data table?

I am working on jQuery Data table to load few data from mysql database.
Here is the html code :
<table id="employee-grid" cellpadding="0" cellspacing="0" border="0" class="display" width="100%">
<thead>
<tr>
<th>#</th>
<th>User Id</th>
<th>Address</th>
<th>Package Name</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
</table>
From php page I'm loading the data like bellow :
// skipping more code...
$nestedData[] = "
<select class='form-control changeStatus' name='status'>
<option value=''>--Select--</option>
<option value='1|$client_id' $statusMsg1>Active</option>
<option value='2|$client_id' $statusMsg2>Blocked</option>
</select>";
Now the loaded data is look like this :
Now I want to call the an Ajax request when html selected option value is change. It's calling Ajax request successfully by bellow code.
jQuery code for jQuery Data Table and My Ajax Request :
$(document).ready(function() {
var dataTable = $('#employee-grid').DataTable( {
"processing": true,
"serverSide": true,
"ajax":{
url :"server_processing.php", // json datasource
type: "post", // method , by default get
error: function(){ // error handling
$(".employee-grid-error").html("");
$("#employee-grid").append('<tbody class="employee-grid-error"><tr><th colspan="3">No data found in the server</th></tr></tbody>');
$("#employee-grid_processing").css("display","none");
}
}
} );
$("#employee-grid").on('change', function() {
var status = $('.changeStatus').val();
alert(status);
$.ajax({
url : "<?php echo SITE_URL . 'toplevel/update-data'; ?>",
data : {
'statusChange' : status
},
type : 'POST',
});
});
});
but When I select the option then every time it's passing first option value
For e.g. This selected option tag has these value :
<option value='1|11' $statusMsg1>Active</option>
<option value='2|11' $statusMsg2>Blocked</option>
It's always passing 1|11 value !! It's should be pass my selected option value. I don't understand why it's happening :(
Note : I think using jQuery data table custom jquery code should be use in different way.
Well Guys,
I have solved it. I need to use something like that :
$('#employee-grid').on('change', '.changeStatus', function(){
// testing.....
var status = $('.changeStatus').val();
alert(status);
});
The solution is to use event delegation by providing selector for target element as a second argument in on() call.

Fill jQuery DataTables with drop down and PHP

I'm working with DataTables and this is my scenario:
1)I've got a drop down menu with some user's name and their proper ID;
2)I've got an empty DataTable;
3)I would like to detect user's ID selecting one row from drop drown menu, pass it to server_processing.php(DB query) using data: property of DataTables and display DB query's result back in Data Table.
Code for drop down:
<select id="selezione_user" name="selezione_user" class="select2 form-control">
<option value="">Seleziona</option>
<?php $query=mysql_query("SELECT user_id,nome FROM user ORDER BY nome",$conn);
while($row=mysql_fetch_array($query)){
echo "<option value='$row[user_id]'>$row[nome]</option>";
}?>
</select>
Code for DataTable (HTML):
<table class="table table-striped" id="prova">
<thead>
<tr>
<th>User</th>
<th>Comune</th>
<th>Mail</th>
<th>Stato</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Code for DataTable (JS)
$(document).ready(function() {
var oTable = $('#prova').dataTable( {
"processing": true,
"serverSide": true,
"ajax": {
"url": "scripts/server_processing.php",
"data": {
"user_id": null //set to show empty DataTable
}
},
});
$('#selezione_user').change(function() {
aoData.push({
"user_id": this.value
})
});
});
But the code above doesn't work and this problem is driving me crazy, I hope someone will help me.
Thanks to all.
Giacomo.
EDIT
I solved my problem using removing data: and changing DataTables(JQuery) function in this way:
$('#selezione_centri').change(function() {
var valore = this.value;
var string = ('scripts/server_processing.php?id_professionista='+valore);
table.ajax.url(string).load();
table.reload();
});
I think you should check the row
echo "<option value='$row[user_id]'>$row[nome]</option>";
Try changing it to
echo "<option value='".$row["user_id"]."'>".$row["nome"]."</option>";
This is somewhat explained here: Accessing arrays whitout quoting the key , the php array keys need to be quoted. This is merely a longshot here!
For more precise debugging (if this is not enough), you should provide the php code.

How can I refresh a datatable inside a div using JavaScript?

Here is my code:
oTable2 = $('#BigData2').dataTable({
"bLengthChange":false,
"bPaginate":false,
"oLanguage": {
"sZeroRecords": "No records found"
},
"sAjaxSource":'StatusSrv',
// "sDom":'RCT<"clear">lfrtip',
//"aoColumnDefs":[{}]
})
var auto_refresh = setInterval(
function (){
$('#Status_Table').fadeOut('slow').load('SupplyPlanning.jsp
#oTable2.fnDraw()').fadeIn("slow");
}, 6000);
<div id="Status_Table" class="chartFloatLeftInner">
<table id="BigData2" >
<thead >
<tr>
<th><input type="checkbox" onClick="checkall()" name="maincheck" id="maincheck"/></th>
<th title="REQ_NO">REQ_NO</th>
<th title="Retailer Partner number">Retailer num</th>
<th title="STATUS">OVERALL_STATUS</th>
</tr>
</thead>
<tbody></tbody>
</table>
I want to refresh my datatable in a particular time interval so that I am using fndraw but it only redraws the table with the old data. If I insert new data in the database, the new data is not shown after refresh; it shows only the old data.
Probably you would need to add the "bDestroy": true attribute to your datatable code which allow you to rebuild it otherwise once created you can not load it with new data.
Try using append:
$('#Status_Table').append( your table in here);
It work for me

Categories

Resources