Auto refresh Table when new row added inside DB - javascript

I have a table that is connected to my DB.
I have 4 columns : Date, Time, Windspeed and Wind direction
Since my table gets a new row on average every 10 second or so I wondered if it was possible to dynamically refresh it without refreshing the whole page using AJAX.
I looked examples and tried to adjust it to my case but it just doesn't seems to work
My table looks like this
<table id="table" align="center" border="1px" style="width:600px; line-height:30px">
<tr>
<th colspan="4"><h2> Résultat : <?php echo htmlentities($nom) ?> </h2> </th>
</tr>
<t>
<th> Date </th>
<th> Heure </th>
<th> Vélocité (km/h) </th>
<th> Direction du vent </th>
</t>
<?php
while($rows=mysqli_fetch_assoc($result))
{
?>
<tr>
<td align="center"><?php echo $rows['Date'] ?></td>
<td align="center"><?php echo $rows['Heure'] ?></td>
<td align="center"><?php echo $rows['Velocite'] ?></td>
<td align="center"><?php echo $rows['Direction_vent'] ?></td>
</tr>
<?php
}
?>
</table>
I tried this kind of refresh :
<script>
$(document).ready(function() {
function RefreshTable() {
$( "#table" ).load( "valeurs.php #table" );
}
$("#refresh-btn").on("click", RefreshTable);
});
</script>

Related

How to delete from json table?

I have a table like below:
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">ID</th>
<th scope="col">Nazwa</th>
<th scope="col">Cena</th>
<th scope="col">Kupujący</th>
<th scope="col"> </th>
</tr>
</thead>
<tbody>
<?php foreach($data as $key => $value): ?>
<tr>
<td><?php echo $value['id']; ?></td>
<td><?php echo $value['name']; ?></td>
<td><?php echo $value['price']; ?></td>
<td><?php echo $value['buyer']; ?></td>
<td><button type="button" name="button2" >Usuń</button></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
how to delete item from this list via clicking on the button in last column of the table?
my php:
$jsonData = file_get_contents("data.json");
$data = json_decode($jsonData, true);
thanks for any help, I don't know how to get value by button clicking :/
It seems that your data is gotten from a file, so to get it done you need to go over all these steps in the same php script:
Get data from this file
Parse data with json_decode
Remove an item using unset($data['id'])
Save new data in the same file
Here is an example:
$jsonData = file_get_contents("data.json");
$data = json_decode($jsonData, true);
// here we go
if(isset($_POST['item_key']) && !empty($_POST['item_key'])) {
$data = array_values($data);
$i=0;
foreach($data as $element) {
//check if it's the right item
if(intval($_POST['item_key']) == $element['id']){ // intval only if you are sure id passed in POST[item_key] always integer
unset($data[$i]);
}
$i++;
}
file_put_contents('data.json', json_encode(array_values($data)));
}
$_POST['item_key'] will come after submiting the form in the html, see below.
In your html code, you will need to add the following:
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">ID</th>
<th scope="col">Nazwa</th>
<th scope="col">Cena</th>
<th scope="col">Kupujący</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<?php foreach($data as $key =>
$value): ?>
<tr>
<td><?php echo $value['id']; ?></td>
<td><?php echo $value['name']; ?></td>
<td><?php echo $value['price']; ?></td>
<td><?php echo $value['buyer']; ?></td>
<td>
<!-- action="#" means you will stay in the same script after submit -->
<form action="#" method="POST">
<input
hidden
type="text"
name="item_key"
value="<?php echo $value['id'];?>"
/>
<input type="submit" value="Remove" />
</form>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
UPDATE
Used unset with array_values after json_decode
Removed header(refre..) since the refresh will be done by form submit to same script

Trying to get value from table on click

I have a table like this:
<table class="table" id = "posts_table">
<caption><h2>cars</h2></caption>
<tr class="success">
<th style="text-align:center"> post_id
<th style="text-align:center"> autor
<th style="text-align:center"> title
</tr>
<?php
$cursor = $MySQLdb->prepare("SELECT * FROM posts WHERE topic_id=:topic_id");
$cursor->execute( array(":topic_id"=>"1") ); //לשנות
foreach ($cursor->fetchAll() as $obj): ?>
<tr>
<td style="text-align:center"><? echo $obj['post_id'] ?></td>
<td style="text-align:center"><? echo $obj['full_name']?></td>
<td style="text-align:center"><? echo $obj['post_title']?></td>
</tr>
<? endforeach; ?>
</table
I want to create function that when u click on the title im getting the post_id for this raw. What should I do to make it happen?
So i try to do this code and it works:
<table class="table" id = "posts_table">
<caption><h2>cars</h2></caption>
<tr class="success">
<th style="text-align:center"> post_id </th>
<th style="text-align:center"> autor </th>
<th style="text-align:center"> title </th>
</tr>
<?php
$cursor = $MySQLdb->prepare("SELECT * FROM posts WHERE topic_id=:topic_id");
$cursor->execute( array(":topic_id"=>"1") ); //לשנות
foreach ($cursor->fetchAll() as $obj): ?>
<tr>
<td class="post_id_c" style="text-align:center"><? echo $obj['post_id'] ?></td>
<td style="text-align:center"><? echo $obj['full_name']?></td>
<td style="text-align:center"><a class="click_title"><? echo $obj['post_title']?></a></td>
</tr>
<? endforeach; ?>
</table>
<script>
$(".click_title").click(function() {
var $item = $(this).closest("tr") // Finds the closest row <tr>
.find(".post_id_c") // Gets a descendent with class="nr"
.text();
console.log($item);
});
</script>

Auto Payslip Printing using Javascript, PHP and MySqli for 500 employees

I am working on a payroll project and I am coding with php,html,js and mysql on xampp server. I have a salary sheet code which needs to be printed in pdf format for each employee with their names as the pdf filename.
on running the php page the js code triggers automatically and generates a pdf file with the filename as the employee name alongwith the employee salary data.
Now I need to generate all the employee payslips together in this format but automatically or maybe by clicking a single button.
I have done this project in vb6,ms-access with success but I am not well versed in javascript and now I am stuck here.
Any Help will be appreciated
<HTML>
<HEAD>
<TITLE>Salary Sheet</TITLE>
</HEAD>
<BODY>
<?php
include "connect.php";
$mysql = "SELECT * FROM emp_ndata LIMIT 0,1";
$myquery = mysqli_query($con, $mysql);
if(! $myquery ) {
die('Could not get data: ' . mysql_error());
}
$row = mysqli_fetch_array($myquery, MYSQLI_ASSOC);
?>
<div id="pdata">
<table class="table_for_showdata table_for_showdata_small">
<tr>
<th colspan="2">
Salary Sheet of <b class="table_for_showdata_lg">
<?php echo $row['Emp_Name']; ?></b> : <?php echo $row ['Emp_psmonth']; ?> , <?php echo $row ['Emp_psyear']; ?>
</th>
</tr>
<tr>
<td>Emp-Code</td>
<td><?php echo $row['Emp_ID']; ?></td>
</tr>
<tr>
<td>Designation</td>
<td><?php echo $row['Emp_Designation']; ?></td>
</tr>
<tr>
<th colspan="2">EARNINGS</th>
</tr>
<tr>
<td >Basic</td>
<td><?php echo round($row ['Emp_Basic']).".00"; ?></td>
</tr>
<tr>
<td >House Rent Allowance</td>
<td><?php echo round($row ['Emp_HRA']).".00"; ?></td>
</tr>
<tr>
<th >DEDUCTIONS</th>
<th> </th>
</tr>
<tr>
<td >Professional Tax</td>
<td><?php echo $row ['Emp_Proffessional_Tax'].".00"; ?></td>
</tr>
<tr>
<td >Provident Fund</td>
<td><?php echo $row ['Emp_Provident_Fund'].".00"; ?></td>
</tr>
<tr>
<th > </th>
<th> </th>
</tr>
<tr>
<td class="tab_head_blue"><b>TOTAL PAY : </td>
<td style="font-size:18px"><b>Rs.<?php echo $row ['Emp_Total_Pay'].".00"; ?></b></td>
</tr>
</table>
</div>
<script type="text/javascript">
function printDiv() {
var divToPrint = document.getElementById('pdata');
var popupWin = window.open('', '_blank', 'width=1100,height=400');
popupWin.document.open();
document.title = "<?php echo $row['Emp_Name']; ?>";
popupWin.document.write('<html><head><title>' + document.title + '</title>');
popupWin.document.write('<html><body onload="window.print()">' + divToPrint.innerHTML + '</html>');
popupWin.document.close();
}
</script>
<script>
printDiv();
</script>
</BODY></HTML>

Update MySQL data from HTML using Javascript

I'm a beginner in HTML, PHP, JavaScript and MySQL. I've written a HTML code to enter data into a simple table containing columns "Name" and "Email" in MySQL by employing a seperate PHP file. Then I tried fetching the table contents using PHP. But now I need a little help in updating the data. My code is as follows:
enter code here<!DOCTYPE html>
<html>
<script language="javascript" src="update.js"></script>
<?php
$a=mysqli_connect("localhost","root","","test4");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($a,"select * FROM test");
?>
<table border="1" cellspacing="1" cellpadding"1">
<tr>
<th>pkid</th>
<th>Name</th>
<th>Email</th>
<th>Action</th>
</tr>
<?php
for ($i=0; $i<mysqli_num_rows($result); $i++)
{
$row = mysqli_fetch_array($result)
?>
<tr>
<td id="pkid"><?php echo $row['pkid'] ?></td>
<td id="name"><?php echo $row['name'] ?></td>
<td id="email"><?php echo $row['email'] ?></td>
<td><input type=submit onclick="myfunc()" value="View"/></td>
</tr>
<?php
}
?>
</table>
<form action="insert.php" method="post">
<table border="2">
<tr>
<td>Name</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email"></td>
</tr>
<tr>
<td>
<input type="submit" value="Add">
</tr>
</table>
</form>
</html>
<?php
mysqli_close($a);
?>
Here is the Code for Update Data to MYSQL :
Html File :
<title>Listing Details for Update</title>
<?php
include ('config.php');
$tbl_name="user"; // Table name
$sql="SELECT * FROM $tbl_name";
$result=mysql_query($sql);
?>
<table width="400" border="0" cellspacing="1" cellpadding="0">
<tr>
<td>
<table width="400" border="1" cellspacing="0" cellpadding="3">
<tr>
<td colspan="4"><strong>List data from mysql </strong> </td>
<td></td>
<td></td>
</tr>
<tr>
<td align="center"><strong>pkid</strong></td>
<td align="center"><strong>Name</strong></td>
<td align="center"><strong>Email-Id</strong></td>
<td align="center"><strong>Action</strong></td>
</tr>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td><? echo $rows['pkid']; ?></td>
<td><? echo $rows['name']; ?></td>
<td><? echo $rows['email']; ?></td>
<td align="center">update</td>
</tr>
<?php
}
?>
</table>
</td>
</tr>
</table>
<?php
mysql_close();
?>
Here you can find the way for Update Single Field, Multiple Field Etc.,
http://php.sysaxiom.com/update_data.php
http://php.sysaxiom.com/update_multiple_data.php
If you need to change the contents of the table to have different rows/row data, (and you want to do it live) you will need to use AJAX. jQuery has fairly straightforward ajax usage, so for actual implementation, I would look to that. You'll also need another PHP file that just returns the raw HTML required to fill in the table. Pseudocode (jquery) below:
$.post("url","dataToPost",function(data){$("#table id where I want to put new data).innerHTML=data});
Basically, the $.post() posts the dataToPost to the url and sets the innerHTML of whatever you select to the resultant data.

PHP - UPDATE a row in a dynamic HTML table

I have a dynamic table that I created in HTML:
<table id="rounded-corner" width="51%" border="1" align="center" cellpadding="2" cellspacing="0">
<tr>
<th width="19%">Job Type</th>
<th width="24%">Job Description</th>
<th width="19%">Type of Piping</th>
<th width="19%">Scheduled Start Time</th>
<th width="19%">Scheduled End Time</th>
</tr>
<?php do { ?>
<tr>
<td nowrap><?php echo $row_selectJobs['JobType']; ?></td>
<td><?php echo $row_selectJobs['JobDesc']; ?></td>
<td><?php echo $row_selectJobs['PipeType']; ?></td>
<td align="center"><?php echo substr($row_selectJobs['TimeStart'],0,-3); ?></td>
<td align="center"><?php echo substr($row_selectJobs['TimeEnd'],0,-3); ?></td>
</tr>
<?php } while ($row_selectJobs = mysql_fetch_assoc($selectJobs)); ?>
</table>
I was wondering if there is a way to add a button to each row so that you can modify the contents of that row. Remember, it's a dynamic table. I'm new to PHP and I really just stole this code from Dreamweaver and modified it for my own needs.
jQuery would be pretty simple to do this for. In your do loop just add another TD and use echo to output something like
<input type='button' class='changeRow' value='Edit' />
For each of the other TD's you will first want to output the values inside a span with a classname something like
<span class="labelValue">..What your PHP actually outputs..</span>
Then a hidden textbox, or something like that depending on how you want to actually do the editing. Each with a className relating to that row. so
<input type='text' class='editInput' value='' style='display: none;'/> etc...
Then using jQuery you can link it all together to make it editable like
$(document).ready(function(){
$('.changeRow').click(function(){
var tb = $(this).parents('tr').find('input.editInput');
var label = $(this).parents('tr').find('span.labelValue');
if($(this).val() == 'Edit'){
tb.val(label.html());
label.hide();
tb.show();
$(this).val('Save');
}
else{
label.html(tb.val());
tb.hide();
label.show();
$(this).val('Edit');
}
});
});
So when your HTML is output, it would look something like this
<td> <!-- The extra td for your edit button -->
<input type="button" class="changeRow" value="Edit">Some Job Type</span>
</td>
<td nowrap>
<span class="labelValue">Some Job Type</span>
<input type="text" class="editInput" value="" style="display: none;" />
</td>

Categories

Resources