Updating HTML table using Jquery & ajax - javascript

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();

Related

How to initialize Datatable after ajax call

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.

Create html table from array from ajax response

In my Laravel app, I add ajax query (which work after pressed button). I get the result in ajax, I see it on console (it's array).
But I need to send an answer from js to PHP for creating a table
This is code of input:
<input type="text" name="check" id="check">
This is code of button:
<button type="button" class="check-client btn btn-success">Find</button>
This is code of ajax (JS):
$(document).on("click", ".check-client", function () {
const data = $("#check").val();
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: 'POST',
data: {
'data': data
},
url: '/checkValues',
success: function (result) {
console.log(result);
const dataForTable = result;
}
});
});
For creating table I try to do this:
send response to php+html:
$(".testClass").append(result);
get this value:
<div class="testClass"></div>
and create a table, using foreach:
<div class="testClass"></div>
<table class="table table-bordered text-center">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">Person</th>
<th scope="col">Cost</th>
</tr>
</thead>
<tbody>
#foreach($dataForTable as $item)
<tr>
<th scope="row">$item['id']</th>
<td>$item['person']</td>
<td>$item['cost']</td>
</tr>
#endforeach
</tbody>
</table>
So, it doesn't work. How to create a table from ajax response?
The problem is that you trying to run jQuery at the client side to uses the return of ajax request (dataForTable) at the server side, it's out of PHP context server. PHP works only server side, meanwhile jQuery is working on browser client, if you want to run javascript in the server side you have to search for other technology, like Node, look at node.js.
Wether you want to update a table on client side using ajax request you have to update a table iterate de variable (dataForTable) on client side, after the request, like this:
$.getJSON( "ajax/test.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
There are many other examples like this above in jQuery.
Finally, you have to work at Client side wether you want to use jQuery, or work at server side using the PHP helpers.

Append AJAX Output to HTML table

I have done my research and I can't seem to find the appropriate answer.
Here is the problem. First off, this question may be broad. And I am new to ajax. I am using laravel and I have just created a controller which handles two dates whereBetween to find the result set and ajax is handling the get request. I am having two issues.
First being, I have no idea on how to append to my existing table. The other issue is a bit complicated. Currently i am using carbons diffForHumans() to display the time taken.
Also using if else statements. Here is how my current table looks like (this is looped from controller for sample data. this is not ajax):
<table class="table">
<thead>
<tr>
<th>Room Number</th>
<th>Cleaned By</th>
<th>Total Time</th>
<th>Supervised</th>
<th>Issues</th>
<th>Cleaned</th>
<th>View</th>
</tr>
</thead>
<tbody>
#foreach($clean as $cleans)
<tr>
<td>{{$cleans->roomnumber}}</td>
<td>{{$cleans->users->name}}</td>
<td>{{$cleans->roomnumber}}</td>
#if($cleans->verified == 1)<td class="verified">Yes</td>#else()<td class="notverified">No</td>#endif
#if($cleans->img1 || $cleans->img1 || $cleans->img1 == !null)<td class="verified">Yes</td>#else()<td class="notverified">No Issues</td>#endif
<td>{{$cleans->created_at->diffForHumans()}}</td>
<td><i class="lnr lnr-eye"></i></td>
</tr>
#endforeach
</tbody>
</table>
As shown above, i have used with() in my controller to get the users name using user_id column. And the diffForHumans(). Also some if else statements.
Here is my AJAX so far:
$(function() {
$('.form').submit(function(event) {
// get the form data in value key pair using jquery serialize
var data = $(this).serialize();
// get the url we are posting to from the forms action attribute
//var url = $(this).attr('/admin/search');
// process the form
var search = $.ajax({
type: "POST", // define the type of HTTP verb we want to use (POST for our form)
url: "search", // the url where we want to POST
data: data, // the url where we want to POST, set in variable above
dataType: "json", // what type of data do we expect back from the server
encode : true
})
// using the done promise callback (success)
search.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});//submit function
});//doc ready end
So how can I append to the above table and still maintain those diffForHumans(), if else statements and most importantly the user name using user_id column (relation)?
Update (Controller):
public function search(Request $request){
$data = $request->only(['from', 'to']);
$data['to'] .= ' 23:59:59';
$output = Clean::whereBetween('created_at', $data)->get();
//return view('admin/search-test', compact('output'));
//return Response($output);
return Response::json(array($output));
}

Pagination with JQuery, PHP not working

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.

How to Refresh a dynamic table without refreshing the whole html page

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.....
}

Categories