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.
Related
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.
My site is set up in the following way:
4 user groups. Each user group can see different information. An example would be stock quantity for a store. So the user from London can't see the stock availability for Manchester. This information is taken from the database for EACH item in stock. So if you have a list of 20 items, their individual values will be displayed.
I would like to do the following:
If I, or anyone I give permission to, hovers over the "In Stock" column for their own store, a tooltip table must appear showing the current stock levels for the 3 other stores, for each individual product. So if I hover over item SKU-001, I will only see the stock availability for that item. I had an issue where it was displaying the whole list for each item.
I was thinking of this:
<table>
<tr>
<th>Store1></th>
<th>Store2></th>
<th>Store3></th>
<th>Store4></th>
</tr>
<?php foreach($this->products as $product) { ?>
<tr>
<td id="stock1" title="myFunction">Stock of Item 1st store</td> *If I hover/mouseover here, another table must appear showing only store name and values of "#stock2, #stock3 and #stock4* for the stock item I am hovering on.
<td id="stock2">Stock of Item 2nd store</td>
<td id="stock3">Stock of Item 3rd store</td>
<td id="stock4">Stock of Item 4th store</td>
</tr>
<?php } ?>
</table>
Here is some code I wrote:
function myFunction() {
var x = document.createElement("TABLE");
x.setAttribute("id", "table10");
document.body.appendChild(x);
var y = document.createElement("TR");
y.setAttribute("id", "myTr");
document.getElementById("myTable").appendChild(y);
var z = document.createElement("TD");
var t = document.getElementByID("riyadhbalance").value();
z.appendChild(t);
document.getElementById("myTr").appendChild(z);
However, for some reason this is not working. I have not found a way to include a tooltip. All the stock values are there for each individual item, so I just need to find a way to add the 3 values for the other stores and display them in a table format via a tooltip. That would be ideal.
So basically the tooltip should show the 3 values of the stores which are currently not on display, as the other 3 values are hidden. The user can only see their store's stock levels. But I would like to include this for myself as it would make it easier to view stock levels across the board.
Check this solution with jQuery and Bootstrap Working fiddle
You have four options:
1 - You can dynamically add it to your code on domReady (like the fiddle)
2 - You can directly print the needed html to make the plugin work. Check docs POPOVER or TOOLTIP
<button type="button" class="btn btn-lg btn-danger my_elements" data-toggle="popover" title="Popover title" data-content="And here's some amazing content. It's very engaging. Right?">Click to toggle popover</button>
// and then, just call from javscript
<script>
$('.my_elements').popover(); // or $('.my_elements').tooltip();
</script>
3 - You can create it when you hover any element. Like the following example (this is particulary helpful if you have a lot of elements needing popover/tooltip, which would consume a lot of time and memory to init and handle)
<table>
<thead>
<tr>
<th>SKU</th>
<th>Description></th>
<th>Stock Tooltip</th>
<th>Stock Popover</th>
</tr>
</thead>
<tbody>
<tr><td>SKU-0001</td><td>This is a description for SKU-0001</td><td class="stock_t">5</td><td class="stock_p">5</td></tr>
</tbody>
</table>
<script>
$('.stock_p').on('mouseover', function(){
// get data from AJAX
// create table element
$(this).attr('title', table_element);
$(this).tooltip({
placement: 'top',
trigger: 'hover',
html: true,
container: 'body',
}).tooltip('show');
});
</script>
4 - with AJAX
<?php
// server side PHP
$other_stores_stock = [ "store_1" => 5, "store_2" => 20, "store_3" => 50 ];
header( 'Content-Type: application/json' );
echo json_encode( $other_stores_stock );
?>
//client side JS - like 1st example
<script>
$('.stock_p').on('mouseover', function(){
$.ajax({
url: your_url,
type: 'POST',
data: { your_data: 'get_stock_qty"},
dataType: "json",
async: false,
success: function (res) {
let table_html = '<table><tr><td>'+res['store_1']+'</td><td>'+res['store_2']+'</td><td>'+res['store_3']+'</td></tr></table>';
$(this).attr('title', 'Stock value for other Stores');
$(this).attr('data-placement', 'left');
$(this).attr('data-toggle', 'popover');
$(this).attr('data-trigger', 'hover');
$(this).attr('data-html', true);
$(this).attr('data-content', table_html);
$(this).popover('show');
}
});
});
</script>
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
});
}
});
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.
I use JQuery DataTable. I send data to datatable onclick in json file at ajax succes .the first click everything is good,But the next click I get only the right data ANd wrong value of dataTables_info it display always the first value of dataTables_info And paginatio AND row too from the first result.
This is the first display of data in datatable:
ALL the next Click I get only right data:
For this exemple they are one result showing in picture below but everything else(info ,show,pagination) belong to first search showing in the first picture :
In the second Exemple When I click at any page of pagination I get the content of the first page result!!
This is my function ONclick:
$ ( '#ButtonPostJson' ).on('click',function() {
$("tbody").empty();
var forsearch = $("#searchItem").val();
$.ajax({
processing: true,
serverSide: true,
type: 'post',
url: 'searchData.json',
dataType: "json",
data: mysearch,
/* bRetrieve : true,*/
success: function(data) {
$.each(data, function(i, data) {
var body = "<tr>";
body += "<td>" + data.name + "</td>";
..........................
..........................
body += "</tr>";
$('.datatable-ajax-source table').append(body);
})
;
/*DataTables instantiation.*/
$('.datatable-ajax-source table').dataTable();
},
error: function() {
alert('Processus Echoué!');
},
afterSend: function(){
$('.datatable-ajax-source table').dataTable().reload();
/* $('.datatable-ajax-source table').dataTable({bRetrieve : true}).fnDestroy();
$(this).parents().remove();
$('.datatable-ajax-source table').dataTable().clear();*/
}
});
});
I try everything and i dont know what I miss.
I use this jquery for datatable:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"></script>
Thanks.
Use like it
$('#product_table').DataTable().ajax.reload();
Get table id first, like:
var table=('#tableid').Datatable();
table.draw();
just put these lines after ajax success function to reload datatable
On a button clik you dont need to empty your table body and make initiate the datatable again with the ajax.
you just have to call your ajax again as you have already initiate on document ready function
just use
$("#Table_id").ajax.reload();
check the below link, you will have better idea.
https://datatables.net/reference/api/ajax.reload()
Let me know if this doesn't help you
I had this same problem. I found a function I wrote on a project that deals with this. Here is a simple 2 column table I made.
<table id="memberships" class="table table-striped table-bordered table-hover" width="100%">
<thead>
<tr>
<th>Member Name</th>
<th>Location</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Member Name</th>
<th>Location</th>
</tr>
</tfoot>
</table>
This is my script to populate it:
function drawTable(){
var table = $('#memberships').DataTable();
table.destroy();
value = $("#memberName").val();
console.log("member name-->>" + value);
$('#memberships').DataTable({
responsive:true,
pageLength: 50,
ajax:{
"url": `//BACKEND API CALL`,
"type":"get",
"dataSrc": 'members'//my data is in an array called members
},
columns: [
{"data": "name_display" },
{"targets": 0,
"data": "membershipID",
"render": function ( data, type, full, meta ) {
return '<button type="button" class="btn btn-info btn-block"
onclick="editMember(' + data + ')">Edit Member</button><button
type="button" class="btn btn-danger btn-block"
onclick="deleteMember(' + data + ')">Delete</button>';
}
}
]
});
$.fn.dataTable.ext.errMode = 'none';
}
You can ignore my column render function. I needed 2 buttons based on the data returned. The key was the table.destroy in the function. I created the table in a variable called table. I destroy it right in this initialization because it allowed me to use this same function over and over. The first time it destroys an empty table. Each call after that destroys the data and repopulates it from the ajax call.
Hope this helps.
Update: After playing with datatables alot more I found that setting table to a variable in a global scope to your function allows you to use reload.
var table = $('#memberships').DataTable({});
Then
table.ajax.reload();
should work.
I created this simple function:
function refreshTable() {
$('.dataTable').each(function() {
dt = $(this).dataTable();
dt.fnDraw();
})
}
use below code..it perfectly work, it keep your pagination without lose current page
$("#table-example").DataTable().ajax.reload(null, false );
$('.table').DataTable().ajax.reload();
This works for me..
$("#Table_id").ajax.reload(); did not work.
I implemented -
var mytbl = $("#Table_id").datatable();
mytbl.ajax.reload;
.reload() is not working properly untill we pass some parameter
var = $("#example").DataTable() ;
datatbale_name.ajax.reload(null, false );
Try This i hope it will work
$("#datatable_id").DataTable().ajax.reload();