In my case, I make auto refresh after X seconds. But I want to make it only refresh when new data inserted or updated.
Here is my script.
refresh.php
<script src="jquery-1.4.js"></script>
<script>
$(document).ready(function() {
$("#responsecontainer").load("refreshnow.php");
var refreshId = setInterval(function() {
$("#responsecontainer").load('refreshnow.php?randval='+ Math.random());
}, 1000);
});
</script>
<div id="responsecontainer"></div>
refreshnow.php
<?php
$query = mysqli_query($connection,"select * from `table`");
$rows = mysqli_num_rows($query);
?>
<table style="background:#F0F0F0;" border=1 style="border-collapse:collapse">
<tr>
<th>Name</th>
<th>Job</th>
</tr>
<tbody>
<?php
while($result = mysqli_fetch_array($query)){
echo "<tr>";
echo "<td>".$result["name"]."</td>";
echo "<td>".$result["job"]."</td>";
echo "</tr>";
}
?>
</tbody>
So, could it be possible to load new data automatically when new data inserted or updated without refresh after x seconds?
If you want to use your existing code, just add another column in a mysql table (if you got a config or settings table, this would be easyer, if not just ad timestamp for each record you insert) with the value time(), this updates the timestamp in the database each time a row is inserted/modified.
Then just do a query like:
"select timestamp_column from `settings_table` order by timestamp_column limimt 1"
If ($result["timestamp_column"]+1000>=time()){
//do the refreshnow.php code here
}
Hope it helps,
Cheers
Related
I'm currently studying a telegram chatbot and I got this idea that I want the bot to send only new data if there is new data in my database which is MySQL and it won't execute the PHP code if there is no new data. But I can't figure out how to do it, for now, I use the meta http-equiv= "refresh". Is there any other method that does something that I need to implement?
I tried to use AJAX long polling method but I don't really understand how to implement it on my project, but I think it might solve my problem. And I already tried to auto-refresh the page every 10 minutes, it works but it will spam the chat with the same data every 10 minutes if there is no new data.
For now this is my code for executing the chatbot so that it will send my data.
<?php
$orang = $db->query('SELECT time_stamp,group_name, message, nvalue, old_svalue, inactive_timestamp, ack_timestamp
FROM alarm ORDER BY time_stamp DESC LIMIT 2');
//$arrayAll = [];
foreach($orang as $orn){
$data = implode(" ",$orn);
$arrayAll[] = $data;
}
//new update function
//execute dibawah
if($orn["nvalue"] < 30){
echo "Tidak dikirim";
}else{
$arrayAll = implode("\n", $arrayAll);
$response = $telegram->sendMessage([
'chat_id' => "$idChat",
'text' => "\n$arrayAll",
'parse_mode' => 'HTML'
]);
}
?>
This is my HTML for showing the data on the database
<body>
<table>
<tr>
<th>Message</th>
<th>Group Name</th>
<th>Time Stamp</th>
</tr>
<?php
foreach($orang as $org){
?>
<tr>
<td>
<?php echo $org["message"];?>
</td>
<td>
<?php echo $org["group_name"];?>
</td>
<td>
<?php echo $org["time_stamp"];?>
</td>
<?php
}
?>
</tr>
</table>
</body>
Thank you.
I'm facing major issue in changing status of a particular row in table with <select> tag .
I'm using jquery-Ajax so, here go functionality by this when is click on <select on any particular row for Example: Lets say i have changed the status of table row of id 2 from Pending to Delivered. On this jquery change() event triggers and it fetchs the value from 'tag' and sends the value to other file through ajax. Till here everything goes right the data goes through ajax and row with particular id's status is getting updated successfully.
But on Front end it does not change the status of the particular row. but it changes status of only first row .
Here i need it to change status of the particular row.
Note : I have searched in stackoverflow for this question. but those answere not come close to my question. Here are those links below Link 1link2link3
THANK YOU IN ADVANCE
Here is the Output and i have explained details in images also
There is the full code
HTML page : index.php
<?php
include('processing.php');
$newobj = new processing();
?>
<html>
<head>
<title>Jquery Ajax select <tag> with PHP Mysql</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<table border="1">
<tr>
<th>Id</th>
<th>Product name</th>
<th>Status</th>
<th>Action</th>
</tr>
<?php echo $newobj->display();?>
</table>
<script>
$(document).ready(function(){
$(".selectstatus").change(function(){
var statusname = $(this).val();
var getid = $(this).attr("status-id");
//alert(displid);
$.ajax({
type:'POST',
url:'ajaxreceiver.php',
data:{statusname:statusname,getid:getid},
success:function(result){
$("#display").html(result);
}
});
});
});
</script>
</body>
</html>
AJAX HANDLER PAGE : ajaxreceiver.php
<?php
include('processing.php');
$newobj = new processing();
if(isset($_POST['statusname'],$_POST['getid'])){
$statusid = $_POST['statusname'];
$id = $_POST['getid'];
$newobj->getdata($statusid,$id);
}
?>
PHP CLASSES FILE : processing.php
<?php
class processing{
private $link;
function __construct(){
$this->link= new mysqli('localhost','root','','example');
if(mysqli_connect_errno()){
die ("connection failed".mysqli_connect_errno());
}
}
function display(){
$sql = $this->link->stmt_init();
$id=1;
if($sql->prepare("SELECT id,productname,status FROM ajaxselect")){
$sql->bind_result($id,$productname,$status);
if($sql->execute()){
while($sql->fetch()){
?>
<tr>
<td><?php echo $id;?></td>
<td><?php echo $productname;?></td>
<td><p id="display"><?php echo $status;?></p></td>
<td>
<select status-id=<?php echo $id;?> id="selectstatus" class="selectstatus">
<option>Pending</option>
<option>Delivered</option>
<option>Cancelled</option>
<option>Amount Paid</option>
</select>
</td>
</tr>
<?php
}
}
}
}
function getdata($statusid,$id){
$sql = $this->link->stmt_init();
if($sql->prepare("UPDATE ajaxselect SET status=? WHERE id=?")){
$sql->bind_param('si',$statusid,$id);
if($sql->execute()){
echo $statusid;
}
else
{
echo "Update Failed";
}
}
}
}
?>
the problem is in this line :
$("#display").html(result);
so what's going here ?
you are creating display id for every row, which is not good practice to do , specially in your particular .
there are various solutions for this problem ,
1)
("#display", $(this).parent().parent()).html(result);
here you are going to apply the action to particular ID which is belongs to the parent of the parent of the particular class which had received the change action
2)
giving the display row unique id for each row
for example like follows :-
<td><p id="display_<?php echo $id; ?>"><?php echo $status;?></p></td>
and then apply your action to it directly ,
$("#display_" + getid).html(result);
3)
and this solution is similar to the past one , by giving the parent <tr> a unique id
for example :-
<tr id='parent_<?php echo $id; ?>'>
and then apply your action it from your ajax like this
$("#display", $('#parent_' + getid)).html(result);
or even :
$('#parent_' + getid + ' #display').html(result);
Yes there is problem in $("#display").html(result); line because id ($("#display")) always select first element found in the DOM you can fix it by - following code-
<script>
$(document).ready(function(){
$(".selectstatus").change(function(){
// make jquery object that make reference to select in which click event is clicked
$this = $(this);
var statusname = $(this).val();
var getid = $(this).attr("status-id");
//alert(displid);
$.ajax({
type:'POST',
url:'ajaxreceiver.php',
data:{statusname:statusname,getid:getid},
success:function(result){
// this refer to the ajax callback function so we have to use $this which is initialized before ajax call
$($this).parents('tr').find("#display").html(result);
}
});
});
});
</script>
I'm trying to make an HTML table dynamically. I'm just testing with sample, but It's not working as well as I expected. So, I'm asking this question. Let me show you this simple table, it is MySQL database. and I create HTML table.
What I want to do is when I click some node, like a '250', this number will be editable. Edited data will be saved to the MySQL database. So I use the contenteditable="true" attribute value, and when this node loses focus, run some JavaScript function that new data will be saved.
But... It's not working well. Honestly I don't know what the problem is exactly. Google chrome spit up "Uncaught Syntax Error, Unexpected token } ", But I couldn't find what the actual problem is. I'm newbie on this... Could you some guys help me?
sample.html
<body>
<?php
require_once("db_connect.php");
$sql = "SELECT * FROM test";
$result = $conn->query($sql);
?>
<table border="1" style="border-collapse:collapse;">
<thead>
<tr><th>name</th><th>price</th></tr>
</thead>
<tbody>
<?php
while($row = $result->fetch_assoc()){
echo
"<tr>
<td contenteditable='true' onBlur='saveToDatabase(this,'name','$id')'>{$row['name']}</td>
<td contenteditable='true' onBlur='saveToDatabase(this,'price','$id')'>{$row['price']}</td>
</tr>\n";
}
?>
</tbody>
</table>
<script>
function saveToDatabase(editableObj, column, id) {
$.ajax({
url: "saveedit.php",
type: "POST",
data:'column='+column+'&editval='+editableObj.innerHTML+'&id='+id,
success: function(data){
$(editableObj).css("background","#FDFDFD");
}
});
}
</script>
</body>
</html>
saveedit.php
<?php
require_once("db_connect.php");
$result = mysql_query("UPDATE test SET ". $_POST["column"]. " = '".$_POST["editval"]."' WHERE id=".$_POST["id"]);
?>
You made it contenteditable but PHP needs an parameter. For example
<input type="text" name="parameter">
will send as $_POST['parameter'] but in your code <td> elements don't have a name. So PHP doesn't know if there is a parameter or what name is.
Maybe you can write your own editable function in Javascript like this:
function doTextArea(i) {
document.getElementById(i).innerHTML="<input type='text' name='table_value'>ssss.";
}
and your php loop can be like this ( I assume it is for loop):
for ($i = 1; $i <= 10; $i++) {
echo
"<tr>
<td><p id=$i ondblclick='doTextArea($i)'> sadasdasdasd</p></td>
</tr>\n";
}
I am displaying posts in a table and then trying to call more posts using ajax, but I am encountering problems here, on clicking show more same posts appear again so how to call next posts by id, and another problem is on clicking show more it changes to loading and remains their, I want it to hide after posts have been loaded.
I am calling the whole table again I think I would be better to call only rows. Here are my two files
index.php
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click','.show_more',function(){
var ID = $(this).attr('id');
$('.show_more').hide();
$('.loding').show();
$.ajax({
type:'POST',
url:'ajax_more.php',
data:'id='+ID,
success:function(html){
$('#show_more_main'+ID).remove();
$('#posts').append(html);
}
});
});
});
</script>
$sql = "SELECT * FROM posts order by id desc limit 6";
$query = $db->prepare($sql);
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC);
$ID = $row['id'];
<div id="posts">
<table>
<tr>
<?php do { //horizontal looper?>
<td>
<div>id</div>
<div>title</div>
<div>body</div>
<div>date</div>
</td>
<?php
$row = $query->fetch(PDO::FETCH_ASSOC);
if (!isset($nested_List)) {
$nested_List= 1;
}
if (isset($row) && is_array($row) && $nested_List++%3==0) {
echo "</tr><tr>";
}
} while ($row); //end horizontal looper
?>
</table>
<div class="show_more_main" id="show_more_main<?php echo $ID; ?>">
<span id="<?php echo $ID; ?>" class="show_more" title="Load more posts">Show more</span>
<span class="loding" style="display: none;"><span class="loding_txt">Loading…</span></span>
</div>
</div>
ajax_more.php
<?php
include('db.php');
if(isset($_POST["id"]) && !empty($_POST["id"])){
$sql = "SELECT * FROM posts order by id desc limit 6";
$query = $db->prepare($sql);
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC);
$ID = $row['id'];
?>
<table>
<tr>
<?php do { //horizontal looper?>
<td>
<div>id</div>
<div>title</div>
<div>body</div>
<div>date</div>
</td>
<?php
$row = $query->fetch(PDO::FETCH_ASSOC);
if (!isset($nested_List)) {
$nested_List= 1;
}
if (isset($row) && is_array($row) && $nested_List++%3==0) {
echo "</tr><tr>";
}
} while ($row); //end horizontal looper
?>
</table>
<div class="show_more_main" id="show_more_main<?php echo $ID; ?>">
<span id="<?php echo $ID; ?>" class="show_more" title="Load more posts">Show more</span>
<span class="loding" style="display: none;"><span class="loding_txt">Loading…</span></span>
</div>
<?php
}
?>
You will have to use OFFSET and LIMIT for your SQL Query. Currently you are using SELECT * FROM posts order by id desc limit 6. That isn't going to load you "more", as it will always only fetch the 6 biggest posts (ordered descending by their id).
You have a couple of problems.
When your AJAX call completes and you want the loading message to disappear, you need to hide that in your success callback of the ajax call. Like so:
$(document).on('click','.show_more',function(){
var ID = $(this).attr('id');
$('.show_more').hide();
$('.loding').show();
$.ajax({
type:'POST',
url:'ajax_more.php',
data:'id='+ID,
success:function(html){
$('#show_more_main'+ID).remove();
$('#posts').append(html);
$('.loding').hide();
}
});
});
In your SQL, you aren't doing anything to select alternative posts because after checking if the ID was sent. You don't do anything with it. Change your SQL to select id's greater than it if it exists.
$postedId = (int)$_POST['id'];
$sql = "SELECT * FROM posts order by id desc WHERE id > $postedId limit 6";
You want to make sure that the id is escaped to prevent any sort of SQL injection. So as a simple measure, I converted it to an integer (I am assuming on that). Otherwise, you should look into using prepared statements for your queries to prevent SQL injection. http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
Your SQL query needs to be fixed. Lets say you want to load the next 6 (ordered in descending order by ID). To do this, you should send some kind of variable like offset. Then you can say:
$sql = "SELECT * FROM posts ORDER BY id DESC LIMIT $offset, $end;"
Where $end = $offset + 6;
Before using this, though, be sure to check that $offset is numeric to prevent SQL injection. This could be implemented using:
if(i!sset($_POST["id"]) || empty($_POST["id"])){
die("No ID value present.");
}
$offset = (isset($_POST['offset']) ? $_POST['offset'] : 0);
if(!is_numeric($offset)){
die("Abnormal input detected.");
} else {
// Input is numeric
$offset = intval($offset);
}
$end = $offset + 6;
$sql = "SELECT * FROM posts ORDER BY id DESC LIMIT $offset, $end;"
/* Your code for actually querying the DB and processing results */
Note: I'm not too familiar with PDO, however, this should be compatible with PDO and safe/secure to use.
I need a web page where users can modify a data already captured in database. So I made a tab with the list of every data and when a user click on one, I want to redirect the user in a page with matching data.
So this is my tab :
<?php
$conn_string = "host=localhost port=5432 dbname=test_postgre user=postgres password='1234'";
$dbconn = pg_connect($conn_string);
$sql = "SELECT id_essai, nom_local_essai, thematique FROM public.essai";
$res = pg_query($sql) or die("Pb avec la requete: $sql");
echo'<table class="table table-hover" border="1">';
echo'<thead><tr><th>id_essai</th><th>Nom local</th><th>Thématique</th></tr></thead>';
while ($data = pg_fetch_array($res))
{
echo' <tbody>
<tr>
<td><a id="'.$data['id_essai'].'">
'.$data['id_essai'].'
</a></td>
<td>
'.$data['nom_local_essai'].'
</td>
<td>
'.$data['thematique'].'
</td>
</tr>
</tbody>
';
}
echo'</table>';
?>
And I get the ID of the data selected like this :
<script>
$(document).ready(function(){
$('a').click(function(){
var id_essai = $(this).attr('id');
$.post('traitement_modif_essai.php',{id_essai:id_essai});
});
});
</script>
Now, on the other file, I want to get the ID and display the right page, but I can't get thought.
<?php
session_start();
$_SESSION['id_essai'] = $_POST['id_essai'];
echo $_SESSION['id_essai'];
header('Location:essai_modif.php');
?>
You can redirect the user after the session has been set by you in the PHP in the javascript callback of post
<script>
$(document).ready(function(){
$('a').click(function(){
var id_essai = $(this).attr('id');
$.post('traitement_modif_essai.php',{id_essai:id_essai}, function(){
window.location = "./essai_modif.php";
});
});
});
</script>
and in the PHP
<?php
session_start();
$_SESSION['id_essai'] = $_POST['id_essai'];
echo $_SESSION['id_essai'];
?>