The Problem: When I click on a pagination link the script is generating the new html table content, but it's not refreshing the table in the browser.
I have class user with method called showUsers($limit, $offset) which is fetching all the data I need and displaying it in table.
<table id="table" class="table table-striped table-bordered table-hover table-sm">
<thead class="thead-default">
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Nickname</th>
<th>User ID</th>
</tr>
</thead>
<?php $user->showUsers($limit, $offset); ?>
</table>
this is my offset varaible: $offset = ($page - 1) * $limit, $page is the number of the pressed pagination link.
This is how I generate the pagination links:
<div class="col-sm-9 mx-auto">
<?php
for ($i=1; $i <= $allPages ; $i++) {
echo "<span class='pag-link' id='$i' style='cursor: pointer; padding: 6px; border: 1px solid #ccc; margin: 3px;'>". $i. "</span>";
}
?>
</div>
This is my JS Script:
//pagination-link handler.
$('.pag-link').click(function(){
var page = $(this).attr("id");
console.log(page);
$.ajax({
type: "POST",
url: "info.php",
data: {page: page},
success: function(data){
console.log(data); // show response from the php script.
}
});
});
setInterval(function(){ $(`#table`).load('info.php #table'); }, 1000);
Note: setInterval(function(){ $("#table").load('info.php #table'); }, 1000); should get the HTML in the table and update the table in the browser with the new table.
So when I click, a page the number is send in the info.php file. This changes my $offset variable and the showUsers($limit, $offset) method will generate new table with different data.
Now this is working because I'm seeing all new HTML that is generated in the javascript console, but setInterval(function(){ $("#table").load('info.php #table'); }, 1000); is not working and my table is not update.
Note: I want to refresh the table in interval, because if multiple users input data I want it to be updated to everyone in real time.
.load('info.php #table') doesn't have the page parameter.
So you load the page ("info.php"), click the next pagination link (url: "info.php",data: {page: page}), and that works, but then the timer loads info.php again, replacing the data.
This will require moving the "var page;" to the top of the Javascript, outside the function call:
//pagination-link handler.
var page=1;
$('.pag-link').click(function(){
page = $(this).attr("id");
console.log(page);
$.ajax({
type: "POST",
url: "info.php",
data: {page: page},
success: function(data){
console.log(data); // show response from the php script.
}
});
});
setInterval(function(){ $(`#table`).load('info.php?page='+page+'#table'); }, 1000);
The PHP that fills $offset will need to respond to both GET and POST, such as $_REQUEST.
Related
I'm trying to get data from Database then append it in table columns using ajax jquery calls. Once i get the data and add it to the Datatable i lose the Datatable functionality which is normal since i'm dynamically adding data and i have to reinitialize the plugin. But the problem is whenever i initialize it i get and error stating "DataTables warning: table id=leadsListTable - Cannot reinitialize DataTable". I went to the link and applied every step they stated, yet i still get an error !
Here's my The HTML
<div class="table-responsive">
<table class="table invoice-data-table dt-responsive nowrap" id="leadsListTable" style="width:100%">
<thead>
<tr>
<th></th>
<th></th>
<th><span class="align-middle">Client#</span></th>
<th>Name</th>
<th>Phone</th>
<th>Adresse</th>
<th>Source</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody id="leadsList">
</tbody>
</table>
</div>
Here's the Ajax function call
function showAllClients(){
$.ajax({
type: 'ajax',
url: '<?php echo base_url() ?>leads/showAllClients',
async: false,
dataType: 'json',
success: function(data){
console.log(data)
var html ='';
for(i=0;i < data.length;i++){
html += '<tr>'+
'<td></td>'+
'<td></td>'+
'<td>'+data[i].lead_ID+'</td>'+
'<td>'+data[i].lead_Name+'</td>'+
'<td>'+data[i].lead_Phone+'</td>'+
'<td>'+data[i].lead_Adresse+'</td>'+
'<td>'+data[i].lead_Source+'</td>'+
'<td>'+data[i].lead_Status+'</td>'+
'<td>Edit</td>'+
'</tr>';
}
$('#leadsList').html(html);
$("#leadsListTable").dataTable({ //Tried this still getting the same error
"destroy": true,
});
},
error: function(){
alert('Could not get Data from Database');
}
});
}
Note that i did read other posts but either the solutions are outdated or they cause the same errors again. Please help !
I think that the problem might be that you destroy the datatable but never reinitialize it.
// Destroy the table
// Use $("#leadsListTable").DataTable().destroy() for DataTables 1.10.x
$("#leadsListTable").dataTable().fnDestroy()
// Reinitialize
$("#leadsListTable").dataTable({
// ... skipped ...
});
See if this works for you.
This question already has answers here:
Does ID have to be unique in the whole page?
(14 answers)
Closed 4 years ago.
I'm implementing delete functionality via AJAX but when i hit delete icon from the table, first element deletion request works fine and at first click it deletes the record, but it doesn't send deletion request for the 2nd or 3rd elements.
JS Ajax Request:
// Delete symptom which is linked with a Remedy ( Causes page )
$("#linked-symptom").click(function(e) {
e.preventDefault();
var symptom_id = $("#linked-symptom").attr('data-id');
var dataString = '&id='+symptom_id;
$.ajax({
type: 'POST',
data: dataString,
url: '<?php echo $this->CxHelper->Route('eb-admin-delete-linked-symptom') ?>',
success: function(data) {
$("#successMessage").show().delay(5000).fadeOut();
}
});
});
HTML Markup:
<table id="cx-records-table" class="table display table-striped table-bordered" width="100%">
<thead>
<tr>
<th>
Title
</th>
<th>
Delete
</th>
</tr>
<?php foreach($symptoms as $key => $symptom){ ?>
<tr>
<td class="all"><?php echo $symptom['title']; ?><br></td>
<td><a class="cx-action row-delete" href="javascript:void(0)" data-id="{{symptom['id']}}" id="linked-symptom"><i class="fa fa-trash-o"></i></a></td>
</tr>
<?php } ?>
</thead>
<tbody></tbody>
</table>
Function:
public function deldeleteLinkedSymptomAction(){
// Get the Evaluation Symptom Id (if any)
$symptomId = $this->request->get('id', null);
$symptom = CxEbEvaluationSymptomCause::getLinkedSymptomEntryForDeletion($symptomId);
if( $symptom ){
$symptom->delete();
return true;
}else{
return false;
}
}
HTML ID should be unique across the page, but you have multiple instances that you then try to use for a jQuery action. It will only affect the first one it finds. Try using this instead:
// Delete symptom which is linked with a Remedy ( Causes page )
$("a.row-delete").click(function(e) {
e.preventDefault();
var symptom_id = $(this).data("id");
var dataString = '&id='+symptom_id;
...
});
I want to update table data without refreshing the page using Ajax and Jquery.
I know I will need setInterval() method, because I want the table to be refreshed to all users, because multiple users could insert data in to the database and I want to update the table to every user.
I have made a script to send the data from a form without redirecting the user or refreshing the page and then insert it in the database.
MyScript.js
$( document ).ready(function() {
console.log( "Ready!" );
//Submitting from data
$("#submitForm").submit(function(e){
if($('#fName').val() && $('#lName').val() && $('#nickname').val()) {
$.ajax({
type: "POST",
url: "process.php",
data: $("#submitForm").serialize(),
success: function(data){
console.log(data); // show response from the php script.
}
});
}
else {
alert("Please fill the fields.")
}
e.preventDefault();
});
});
In my process.php file I insert the data to the database.
Now I have info.php file that generates my table with all the data and I have a form there to insert new data.
<div id="table" class="col-md-7 ml-5">
<table class="table table-striped table-bordered table-hover table-sm">
<thead class="thead-default">
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Nickname</th>
<th>User ID</th>
</tr>
</thead>
<?php $user->showUsers(); ?>
</table>
</div>
the showUsers() function just generate the other rows of the table with the data from SQL.
I have no idea how to refresh the table using Jquery and Ajax.
I tried to use the .load() method, but it also generates the html for my form.
Please help.
As you said, you can use setInterval or better setTimeout since you want the return of the data to trigger a new request later
var tId="";
function getInfo() {
$.get("info.php #table",function(data) {
tId = setTimeout(getInfo,60000);
$("#someContainer").append(data);
});
}
getInfo();
Okay I have a html table given below:
<table class="table">
<thead>
<tr>
<th>Product</th>
<th>Quantity</th>
<th colspan="2">Total</th>
</tr>
</thead>
<tbody id="cart_table">
...
</tbody>
<tfoot>
<tr>
<th colspan="2">Total</th>
<th colspan="2">$446.00</th>
</tr>
</tfoot>
</table>
I am using ajax to append values clear tbody at every click of a button and refill the tbody with multidimensional session array. It works fine for 1st turn, but does not work for 2nd click
My jquery code is given below
<script>
$(document).ready(function(){
$('.addToCart').on('click',function(e){
$("#cart_table").empty();
var price = $(this).attr('data-price');
var item = $(this).attr('data-itemname');
e.preventDefault();
$.ajax({
method : "POST",
async: false,
url: "./php/addToCart.php",
dataType : "json",
data : {item:item,price:price},
success : function(response){
$("#cart_table").empty();
<?php
$i = 0;
foreach ($_SESSION["cart_array"] as $each_item):
$item = $each_item['item'];
$price=$each_item['price'];
$quantity=$each_item['quantity'];
?>
$('#cart_table').append("<tr><td><?php echo $item; ?></td><td><?php echo $quantity; ?></td><td><?php echo $price; ?></td><td><a href='#'><i class='fa fa-trash-o'></i></a></td></tr>");
<?php
endforeach;
?>
}
});
});
});
</script>
I have checked my session values are updated. However, the change is not shown on my table except for first click.
As pointed out in comments PHP is server side language, for it to reflect the changes, your page needs to reload but because you are using ajax page is not going to reload (Or rather we don't need it to reload).
It work for the first time because for the first time when page is loaded, the current data will already be present in your JavaScript function :
Right here :
$('#cart_table').append(<?php echo "<tr><td>".$item."</td><td>".$quantity."</td><td>".$price."</td><td><a href='#'><i class='fa fa-trash-o'></i></a></td></tr>";?>);
So what happens here is that when you click for the first time, your ajax will execute and success function is called, this function will add the already presented data because it will not update unless your page is reload. So every time you click, your session will be updated and success function is also called but your table will not reflect the changes.
So, You need to change your PHP code To JavaScript, Here the basic idea of what to do, (Here i have assumed your response is JSON, And also note that following code will not work out of the box because i didn't tested it.)
<script>
$(document).ready(function(){
$('.addToCart').on('click',function(e){
$("#cart_table").empty();
var price = $(this).attr('data-price');
var item = $(this).attr('data-itemname');
e.preventDefault();
$.ajax({
method : "POST",
async: false,
url: "./php/addToCart.php",
dataType : "json",
data : {item:item,price:price},
success : function(response){
$("#cart_table").empty();
//New JavaScript code, make appropriate changes.
jQuery.each(response, function(key, row) {
$('#cart_table').append("<tr><td>" + row.item + "</td><td>" + row.quantity + "</td><td>" + row.price + "</td><td><a href='#'><i class='fa fa-trash-o'></i></a></td></tr>");
});
}
});
});
});
I have a dynamic table that displays data from a mysql database. My database is updated every time in the server. I want to refresh only the table every 2 seconds without refreshing the whole page. How can do this? Please help how accomplish this?.
Parts of my table look like this:
<table id="getdata" border="0" align="left" cellpadding="0" cellspacing="0">
<tr>
<td bgcolor="#CCFF00">Name</td>
<td bgcolor="#CCFF00">Comment</td>
<td bgcolor="#CCFF00">DatePosted</td>
</tr>
</table>
You will need to use a client-side scripting language such as javascript in order to be able to refresh certain contents on your HTML page. A very common library that is used is jQuery.
PHP
# ajax.php
$contents = '<table class="table table-hover">
<thead>
<tr>
<th>Sound</th>
</tr>
</thead>
<tbody>
<tr>
<td>Bzzz Bzz</td>
</tr>
</tbody>
</table>';
echo json_encode($content);
HTML/Javascript
<button class="refresher">Refresh table</button>
<table id="table-to-refresh">
<thead>
<tr>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
</tr>
</tbody>
</table>
<script type="text/javascript">
$(document).ready(function () {
$(document).on('click', '.refresher', function () {
$.ajax({
url: 'ajax.php',
method: get,
dataType: 'json',
success: function(response) {
$('#table-to-refresh').html(response);
}
});
});
});
</script>
Additional reading
jQuery Docs - Ajax
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#load_tweets').load('file.php').fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds
</script>
in file put your full html and php sql code like full code by which you are generating that table.
check this for refrence http://www.9lessons.info/2009/07/auto-load-refresh-every-10-seconds-with.html
Use ajax on an specified time interval like:
$.ajax({
url: 'your_url',
method: get,
data:
{
var1 : val1
},
success: function(response)
{
$('#getdata').html(response); // it will update the html of table body
}
});
just do this:
$.ajax({
contentType: contentType,
dataType: dataType,
type: type,
url: urlGetsearch,
data: '{textvalue: "' + $("#tableId").val() + '" }',
success: function (textvalue) {
$("#tableId").html(htmlData);
},
});
}
The controller is look like this:-
[HttpPost]
public ActionResult Getsearch(string textvalue)
{
your code.....
}