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

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

Related

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.

unable to export html table using jquery and php $_GET

my downloaded table only prints headers and does not display any content.
iam following the tutorial from here:http://webslesson.blogspot.in/2016/02/export-mysql-data-to-excel-in-php-php-tutorial.html
THE FOLLOWING PLUGINS i have tried which fails to render my huge data
1.clarketm(merges rows)
2.(tried but unable to render huge dat)https://github.com/kayalshri/tableExport.jquery.plugin
my HTML DOM IS (index.php)
<div id="allTables">
<table border="2" width="100%">
<tr>
<th width="30%">Name</th>
<th width="20%">Activity on Code Project (%)</th>
<th width="10%">Activity on C# Corner (%)</th>
<th width="10%">Activity on Asp Forum (%)</th>
</tr>
<tr>
<td>Sibeesh</td>
<td>100</td>
<td>98</td>
<td>80</td>
</tr>
<tr>
<td>Ajay</td>
<td>90</td>
<td>0</td>
<td>50</td>
</tr>
</table>
</div>
<p id="exportexcel">EXport to Excel</p>
<script>
$(document).ready(function () {
$('#exportexcel').click(function(){
var excel_data = $('#allTables').html();
console.log(excel_data);
var page = "excel.php?data="+excel_data;
console.log(page);
window.location = page; // here iam sending data to excel.php through get method
});
</script>
my excel.php file is
<?php
header('Content-Type: application/vnd.ms-excel');
header('Content-disposition: attachment; filename='.rand().'.xls');
echo $_GET["data"];
?>
--please help me what iam doing wrong thanks in advance
Activity on C# Corner (%) - "#" in this line is causing the problem. encoding this will resolve the issue in above code.
But its better to use POST as suggested.
If you pass html code via get then you must encode it else you can use post method.
following code would be useful to you.
<script type="text/javascript">
var htmlString= document.getElementById(allTables).innerHTML;
$.ajax({
type: "POST",
url: "excel.php",
dataType:'html',// ***add this option!***
data: {html:htmlString},
success: function (data) {
// this is executed when ajax call finished well
alert('file has been saved');
location.reload();
},
error: function (xhr, status, error) {
// executed if something went wrong during call
if (xhr.status > 0) alert("Error: " + status); // status 0 - when load is interrupted
}
});
}
</script>
Your excel.php file should be
<?php
header('Content-Type: application/vnd.ms-excel');
header('Content-disposition: attachment; filename='.rand().'.xls');
echo $_POST["html"];
?>
and if you want to use $_GET then you should refer
how can I javascript decodeURI in PHP?
to encode and decode uri in javascript to php

How do you transfer data from a table to a server?

I am trying to fetch data from a table and push the selected data to my server.
I have tried selecting columns from my table then making an HTTP request, but it didn't work.
Can anyone help me?
This is my understanding
here is a procedure if you like to do
insert all you desire record set into an array
make a json using json_encode() method of php.
use curl post request and pass the json string
Here's an example of how to pull data from a HTML table, put it into a javascript array, convert it to json and send it to the server
https://jsfiddle.net/f958qokn/
<table id="MyTable">
<tr>
<td>1</td>
<td>Code Monkey</td>
</tr>
<tr>
<td>2</td>
<td>Code Elephpant</td>
</tr>
</table>
<input id="PostTableData" type="button" value="Post Table Data"/>
<script type="text/javascript">
$(document).ready(function() {
$( "#PostTableData" ).on( "click", function() {
var TableData = [];
$("#MyTable tr").each(function() {
var RowData = [];
var ColumnsData = $(this).find('td');
if (ColumnsData.length > 0) {
ColumnsData.each(function() { RowData.push($(this).text()); });
TableData.push(RowData);
}
});
alert(JSON.stringify(TableData));
jQuery.ajax({
type: 'POST',
url: "/SaveData.php",
data: JSON.stringify(TableData),
dataType: "json",
success: function(data){ alert(data); }
});
});
});
</script>

On page refresh html tag IDs,classes and names are not getting preserved

I am taking the data from textbox and option field using AJAX request to the server storing it to db, creating the row and attaching it to table.
$("#addRecord").click(function(e) {
e.preventDefault();
var question_id = $("#questionId").val();
var question_text = $("#questionText").val();
$.ajax({
url: "addContestAnswer.html",
type: "post",
dataType: "json",
data: {"questionId": question_id, "contestText": question_text},
success: function(data){
addRows(data.questionId,data.contestText);
// calling the function to create row
},
error: function (request, status, error) {
console.log("error" + status);
}
});
});
creating the row
function addRows(questionId ,questionText) {
var deleteButton = 'delete';
var fileUpload = '<input type="file" name="supportingDocument" accept="application/pdf" id="uploadSupportingDoc" />';
var row = "<tr><td class=\"ques_id\">"+questionId+"</td><td class=\"ques_text\">"+questionText+"</td><td class=\"ques_file\">"+fileUpload+"</td><td></td><td>"+deleteButton+"</td></tr>";
$('#recordTable tr:last').after(row);
$("#questionId").val("-1");
$("#questionText").val("");
}
So far the html generated is looking good.
But when I'm refreshing the page, none of the html IDs,classes and Names of generated row are getting preserved.
generated row after ajax call
<tr>
<td class="ques_id">17</td>
<td class="ques_text">asddgfdg</td>
<td class="ques_file"><input type="file" name="supportingDocument" accept="application/pdf" id="uploadSupportingDoc"></td>
<td></td>
<td>delete</td>
</tr>
After refreshing the page
<tr>
<td>17</td>
<td>asddgfdg</td>
<td><input type="file" name="" id=""></td>
<td></td>
<td>delete</td>
</tr>
why is it happening? am I missing some tweak while generating the row, if not what's the solution?

Table not rendering properly with Mustache.js and Boostrap

I'm trying to use Mustache.js but while my table is being created is not applying the Boostrap class properly. Only the header gets the css. I tried applying the class with jquery after the button click but did not help. I also try embedding the template inside the table but id did not work.
I have this html.
<table id="mTable" class="table table-striped">
<tr>
<th>FY</th>
<th>COST</th>
</tr>
</table>
then my template
<script id="priceTemplate" type="text/template">
<tr>
<td>{{FY}}</td>
<td>{{COST}}</td>
</tr>
</script>
my Ajax code.
$('#cmdSubmit').on('click', function () {
event.preventDefault();
var PriceTemplate = $('#priceTemplate').html();
$priceTable = $('#mTable');
$.ajax({
type: "GET",
url: "mywebservice.asmx/GetData",
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function (msg) {
var pricedata = eval(msg.d);
$.each(pricedata, function (i, price) {
$priceTable.append(Mustache.render(PriceTemplate, price));
});
}
});
});
my table is showing data but is looks like the template is not getting stylized by bootstrap.
TIA,

Categories