I have a column in phpMyAdmin id call that gets integer values 1 or 0. When 1, the user enter the site an alert is displayed ('Welcome!'); how to do so that when the user clicks OK to be updated msg to 0?
index.html
<!DOCTYPE html>
<html>
<body>
<h1>Getting server updates</h1>
<div id="result"></div>
<script>
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("demo_sse.php");
source.onmessage = function(event) {
var msg = event.data;
if (msg>0){
alert('Welcome');
};
};
};
</script>
</body>
</html>
demo_sse.php
<?php
$dominio = "127.0.0.1";
$host = "localhost";
$user = "root";
$pass = "";
$banco = "teste";
$codificacao = 'utf8';
$conexao = mysqli_connect($host, $user, $pass, $banco) or die(mysqli_connect_error());
$sql= "select * from `msg`";
$resultado = mysqli_query($conexao,$sql);
$tabela = mysqli_fetch_array($resultado);
$id=$tabela['id'];
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$time = date('r');
echo "data:{$id}\n\n";
flush();
?>
You'll have to create a php script that switches that record to 0 then use the event of clicking the ok button to fire an Ajax request to that script. The Ajax will run your php and give the effect you want. If you need more instruction I can do a detailed example when I get to a computer.
Related
I have the PHP code where I get echo as my postgres database table fields I want to display these fields in my html and JavaScript based web application.for now I can load them in my webpage but I have to reload the webpage to get newly updated values. I want to get them automatically in a textbox without reloading application.i read that an ajax request would be helpful
given is the php code i am using with html to show case records but i have to reload page every time to get it updated
<?php
$host = "host = localhost";
$port = "port = 5432";
$dbname = "dbname = geoserver";
$credentials = "user = postgres password=password";
$db = pg_connect( "$host $port $dbname $credentials" );
$sql =<<<EOF
SELECT * from audit.logged_actions
ORDER BY action_tstamp_tx DESC
LIMIT 5;
EOF;
$ret = pg_query($db, $sql);
if(!$ret) {
echo pg_last_error($db);
exit;
}
while($row = pg_fetch_row($ret)) {
// echo "e = ". $row[1] . "\n";
echo "<input type='text' value='$row[14] '/>";
echo "<input type='text' value='$row[13] '/>";
}
echo "Operation done successfully\n";
pg_close($db);
?>
The problem is that after your browser renders the output of your php script, it is not connected to your php anymore. This is how HTTP works.
To be able to show the output without refreshing the whole page, you need to use javascript to make another HTTP request to your PHP script.
Something like this:
<?php
$host = "host = localhost";
$port = "port = 5432";
$dbname = "dbname = geoserver";
$credentials = "user = postgres password=password";
$db = pg_connect( "$host $port $dbname $credentials" );
$sql =<<<EOF
SELECT * from audit.logged_actions
ORDER BY action_tstamp_tx DESC
LIMIT 5;
EOF;
$ret = pg_query($db, $sql);
if(!$ret) {
echo pg_last_error($db);
exit;
}
?>
<div id='content'>
<?php while($row = pg_fetch_row($ret)) { ?>
<input type='text' value='<?= $row[14] ?>'/>
<input type='text' value='<?= $row[13] ?>'/>
<?php } ?>
Operation done successfully
<script>
(function() {
const secondsToRefresh = 5;
const Http = new XMLHttpRequest();
const url='#YOUR_PHP_SCRIPT_URL#';
setTimeout(function() {
Http.open("GET", url);
Http.send();
}, secondsToRefresh * 1000);
Http.onreadystatechange=(e)=>{
document.getElementById('data').innerHTML = Http.responseText;
}
})()
</script>
</div>";
I try to use server side event with updating or adding data in database. In this case, why the onmessage event in index.html doesn't work after I add data to database by dataAdd.php?
index.html :
<body>
<div id="result"></div>
</body>
<script>
var result = document.getElementById("result")l
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("sse.php");
source.onmessage = function(event) {
result.innerHTML += event.data + "<br>";
};
} else {
result.innerHTML = "Sorry, your browser does not support sse";
}
</script>
sse.php :
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
mysql_connect("localhost","username","password");
mysql_select_db("database");
mysql_query("set names utf8");
$result = mysql_query("select * from table order by id desc limit 1;");
$row = mysql_fetch_array($result);
echo "data: $row[message]";
flush();
?>
dataAdd.php :
<?php
mysql_connect("localhost","username","password");
mysql_select_db("database");
mysql_query("set names utf8");
if(isset($_GET['text'])) {
mysql_query("insert into chat (message) values ('$_GET[text]')");
}
?>
Hi I have the following code which I am trying to adapt to make sure that when Like is clicked by a user who is logged in, then only one request is sent in a predetermined period of time that can be adjusted i.e Like can be clicked and a request sent only once every 5 minutes. There must be a javascript function I can use but I can't figure it out.
index.php:
<?php
include 'init.php';
include 'connect.php';
?>
<!doctype html>
<html>
<body>
<?php
$userid = $_SESSION['user_id'];
echo '<a class="like" href="#" onclick="like_add(', $userid,');">Like</a>';
?>
<script type ="text/javascript" src="jquery-1.11.1.min.js"></script>
<script type ="text/javascript" src="like.js"></script>
</body>
</html>
connect.php:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "DB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
init.php:
<?php
session_start();
$_SESSION['user_id']='1';
$userid = $_SESSION['user_id'];
include 'connect.php';
include 'like.php';
?>
like.js:
function like_add(userid) {
$.post('like_add.php', {userid:userid}, function(data) {
if (data == 'success'){
add_like($userid);
} else {
alert(data);
}
});
}
like.php:
<?php
function add_like($userid) {
include 'connect.php';
$stmt = $conn->prepare("INSERT INTO clicks (user) VALUES (?)");
$stmt->bind_param("s", $userid);
$stmt->execute();
$stmt = $conn->prepare("SELECT max(id) FROM clicks WHERE user=?");
$stmt->bind_param("s", $userid);
$stmt->execute();
$stmt->bind_result($click);
$stmt->fetch();
echo $click;
$stmt->close();
}
?
like_add.php
<?php
include 'init.php';
if (isset($userid)) {
$userid = $userid;
add_like($userid);
}
?>
If you pass the a tag into like_add like so:
<?php
$userid = $_SESSION['user_id'];
echo '<a class="like" href="#" onclick="like_add(this, '.$userid.');">Like</a>';
?>
You can disable it in the javascript function for a set time period:
function like_add(a, userid) {
a.disabled = true;
setTimeout(function(){
a.disabled = false;
), 5000});//Code will execute in 5 seconds to enable the a tag
$.post('like_add.php', {userid:userid}, function(data) {
if (data == 'success'){
add_like($userid);
}else{
alert(data);
}
});
}
Is this something alogn the lines of what you were looking for?
In a completly not recommended way, you could define
var isLikeable = true;
function likeStatus(secs) {
isLikeable = false;
window.setTimeout("isLikeable = true;", (secs*60));
}
then, when clicking the "like" you would check
if (isLikeable) { // do like and call likeStatus(300); }
Do you need this to be enforced on the back-end, or is disabling it through the UI sufficient? You could theoretically get people hacking it using Developer tools or Firebug, but this seems very unlikely from casual users.
On the front end, I would user jQuery to add code on the click event that disables the "Like" button with a timeout, like this:
// First, move your click handler to your script file
$('.like').click( function(event) {
// Make sure clicking the button doesn't submit any form context that might be present
event.preventDefault();
var DURATION_IN_MINUTES = 5;
// Grab the user id that will be added as an attribute of your element: data-user-id="$userid"
var user_id = $(this).data('userID');
// Run your function
like_add(user_id);
// Disable clicking like (it's easiest to do this with a button, by far
$(this).prop({'disabled':true,'title':'Disabled for ' + DURATION_IN_MINUTES + ' minutes');
// Set a timer to re-enable the like button in 5 minutes
setTimeout( function() { $(this).prop({'disabled':false,'title':''}), DURATION_IN_MINUTES * 60 * 1000}
});
and then in your HTML:
echo '<a class="like" href="#" onclick="like_add(', $userid, ');">Like</a>';
becomes
echo '<button class="like" data-user-id="' + $userid + '">Like</button>';
I don't have a PHP environment to test this (and I haven't tested the JavaScript itself, to be honest), but this should be enough to get you started.
If you want to block multiple submissions on the back-end, you'll want to timestamp your likes, and do a look-up to see the last time a given user "liked" that link.
So following my last question I want to use the value that is submitted in the input tag to get the matching id in my database. I have created two files for it but I can't figure out how to link them. Also note I made a database with a few values(id, firstname, etc.) and when the user fills in 1 I want it to display id 1 & the firstname.
This code is from the last question & I've added xmlhttp:
Input code
Choose a number between 1 and 5
Your info shall be shown here
Click me!
var myButton = document.getElementById('btn');
myButton.onclick = function(){
alert(document.getElementById('myid').value);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if( xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var dbText = xmlhttp.responseText;
document.getElementById('dbinfo').innerHTML = dbText;
}
}
xmlhttp.open("POST", "LinkToDataFile", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
}
That is what the user sees and the number is displayed correctly however I now need to link it to my file data.php which I have tried but it cannot get the value.
Data Code
<?php
require_once('input_code');
//Get the data from the database and echo them here
$servername = "localhost";
$username = "root";
$password = "";
$databasename = "db_name";
try
{
$connection = new PDO("mysql:host=".$servername.";dbname=".$databasename, $username, $password);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement = $connection->prepare("SELECT `id`, `firstname`, FROM `db_name` WHERE `id` = :myid"); //Here it needs to grab the value but it does not work.
$statement->bindParam(':id', $id);
$id = $_POST['id'];
$statement->execute();
$result = $statement->setFetchMode(PDO::FETCH_ASSOC);
$data = "";
foreach($statement->fetchAll() as $key => $value)
{
$data .= $value['id']." | ".$value['firstname'];
}
}
catch(PDOException $e)
{
echo "The following error occurred : ".$e->getMessage();
}
echo $data;
?>
So what am I doing wrong? am I missing something obvious like the $id again or is it a series of errors, the only thing it does now is giving me an alert with the number.
By adding a line and moving $id before $statement it is all fix thanks to Dante Javier
Input code
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); //Under this add the following lines:
var id = document.getElementById('myid').value;
xmlhttp.send("id="+id);
Data Code
$id = $_POST['id']; //Move this above the $statement = $connection->prepare.
I am using HTML5 Server-Sent Events.
Actually I need to show notification (new record enter and which are unread) that's when any new record is insert in database (php/mysql).
So for testing purpose I just tried with count of total row. But I am getting this error message in my local-host:
Firefox can't establish a connection to the server at http://localhost/project/folder/servevent/demo_sse.php.
The line is:
var source = new EventSource("demo_sse.php");
I have tried this:
index.php
<script>
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("demo_sse.php");
source.onmessage = function(event) {
document.getElementById("result").innerHTML = event.data;
};
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>
<div id="result"></div>
demo_sse.php
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$db = mysql_connect("localhost", "root", ""); // your host, user, password
if(!$db) { echo mysql_error(); }
$select_db = mysql_select_db("testdatase"); // database name
if(!$select_db) { echo mysql_error(); }
$time = " SELECT count( id ) AS ct FROM `product` ";
$result = mysql_query($time);
$resa = mysql_fetch_assoc($result);
echo $resa['ct'];
flush();
?>
Please let me know what going wrong.
I know for notification we can use Ajax with some interval time, but I don't want such thing. As I have N number of records and which may slow my resources.
According to this,
There are several 'rules' that need to be met, and yours is lacking at this point:
Output the data to send (Always start with "data: ")
It is somehow like:
echo "data: {$resa['ct']}\n\n";
Setting a header to text/event-stream worked for me:
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
// Rest of PHP code
Please modify the following code snippet according to your requirements
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
// infinite loop
while (1) {
// output the current timestamp; REPLACE WITH YOUR FUNCTIONALITY
$time = date('r');
echo "data: Server time: {$time}\n\n"; // 2 new line characters
ob_end_flush();
flush();
sleep(2); // wait for 2 seconds
}
?>
I tested this code snippet myself; it's working for me. If you have any query, let me know.