I'm trying to follow the first answer here in order to accomplish my alert feature on my app. Facebook like notifications tracking (DB Design)
but in that example, the user has to open the notifications page to check for new notifications. For me, i need to let user knows that there is a notification (database updated) by displaying an icon like Facebook alerts or something like that.
is there any clear idea about how to do that ?
EDIT
i did something but can't test it coz i don't have my laptop right now.
would you please take a look and let me know if something not OK ?
PHP file
$userID=$_GET["userid"];
//Database connection
$sql = 'SELECT count(*) as count FROM list_notifications WHERE userid ='.$userID;
$qry = pg_query($sql);
$row = pg_fetch_array($qry);
echo $row['count'];
jQuery & JavaScript
var old_count = -1;
setInterval(function() {
$.get("file.php", { userid: "userid" },
function(data){
if (data > old_count) {
alert("the list is updated with: " + data);
//OR
//console.log('the list is updated with:' + data);
old_count = data;
}
}
)},5000); // every 5 seconds
once the user is logged in, the userid must be sent periodically to the php file to check for new notifications. then display them to the user.
for count variable, i made it Increases incrementally with Database trigger.
Related
I have a php file, which updates the SQL, if the "follow this user" button is clicked, and an AJAX calls this PHP file. The code below works, it follows the user! My problem is: If, for some reason the SQL update fails, I want the AJAX to drop an error message (e.g. an alert), but I really don't know how this could be possible. The AJAX doesn't know whether the update succeeded or not.
Here's my code:
PHP
if(!empty($_GET['a']) and $_GET['a']=='follow')
{
$id = sql_escape($conn,$_GET['id']);
$me = $user2[0];
//the user's id who clicks on the follow button
$query = sql_fetch(sql_query($conn, "select * FROM
forum where id='$id'"));
//check who created this forum, so we know who to follow
$follow_this_user = $query['user'];
//the user to follow
$now = date('Y-m-d H:i:s');
$already_follow_user = sql_fetch(sql_query($conn,
"SELECT * FROM follow WHERE user_id=".$me." AND
followed_user =".$follow_this_user." "));
//check if user already followed by this user
if(empty($already_follow_user[0])) {
//if not followed
sql_query($conn,"INSERT INTO follow
(user_id, followed_user, date) VALUES
('".$me."', '".$follow_this_user."', '".$now."');")
or die(mysqli_error($conn));
}
}
AJAX:
$(document.body).on('click', '.followable', function(){
//User clicks on the follow text, which has "followable" class
$.ajax({
//type: 'GET',
url : '/ajax/ajax_follow.php?a=follow&id=<?php print $topic[id]; ?>'
//the $topic['id'] is the id of the current topic, which
//I need to know who created this forum, to follow that user
//(as mentioned above in the php code)
});
I need data and error, but no idea how to get them working. I tried many things, but I just can't get the data.
Add this to your ajax request:
success: function(data) {
alert(data);
}
And simply echo something on your PHP page.
For example:
$result = mysql_query($sql);
echo $result;
If you want to recieve more data, JSON is your friend.
I want to update a MySQL field after when the site was opened for X Seconds.
I get the Seconds/Time from MySQL and want to update in MySQL when the seconds are over.
I tried
sleep($adddisplaytime);
but then the site waits complete and does not run the things over first
Is there a way to run my update after some seconds when the site is opened?
$query1 = "UPDATE ads SET views = views+1, costs = costs+price WHERE id = '".$adid."'";
Can be in PHP or MySQL
NOTE: This will do what you want, but could be exploited by someone hitting the AJAX endpoint repeatedly, you would want to build in some protections for that.
You will need an additional PHP file, the job of that PHP is to only update the db. You will need to take that update OUT of your page loading script.
Your HTML / JS / PHP for initial load
<script>
setTimeout(function() {
$.ajax('/your/ajax/endpoint.php', {
data: {
'adid': 'your id'
/*
If this is in your PHP file, you can echo the ID straight there.
Not totally recommended, but that's one way An additional /
better way is to add it to a div with a data attribute and
use jQuery to select the data off of there
*/
}
}); // Probably lots more you can do here, but in this case, for simplicity, just sending and that's it
}, 2000); // This will do a 2 second wait
</script>
Your new additional PHP file that is at /your/ajax/endpoint.php
<?php
// THIS FILE DOES THE UPDATE
$adid = $_POST['adid'];
// As mentioned by tadman in his comment.. I would use prepared statements
$query1 = "UPDATE ads SET views = views+1, costs = costs+price WHERE id = ?";
try {
$dbh = new PDO($dsn, $user, $password);
$sth = $dbh->prepare($query1);
$sth->execute(array($adid));
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
NOTE:
Again, for security's sake, you really want to consider having your first PHP script generate a unique ID (and store it in the db), that is passed to the page, and having the AJAX send that unique ID with the adid, and if the unique ID you gave is in the database only THEN would you know it's a legitimate request. Remove the unique ID from the database and do the update.
If you want to wait for some seconds after a page is opened and then run the update statement , then write the following codes on the top of the page:-
echo "<script> setTimeout(function(){}, 2000) ; </script>" ;
$query1 = mysqli_query($con, "UPDATE ads SET views = views+1, costs = costs+price WHERE id = '".$adid."'");
i am using database trigger
when database row updated i want to get real time notification like change happened now
suppose i am using message table in my database
suppose user inserted value in message table. i want change should be noted using
trigger at real time and then i want open an html page when row inserted in my
message table then html page should open or an alert box show notification
that"you received a new message".
Please help me to solve this problem
for example
CREATE TRIGGER notifyMe
ON table1
AFTER INSERT, UPDATE, DELETE
AS
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'DB AutoMailer',
#recipients = 'user#example.com',
#body = 'The DB has changed',
#subject = 'DB Change';
in above example mail is sending but i want to open html page i need syntax to open html page
Well below is a example of what you need exactly:
javascript
var old_count = 0;
setInterval(function(){
$.ajax({
type : "POST",
url : "file.php",
success : function(data){
if (data > old_count) {
alert('new record on i_case');
old_count = data;
}
}
});
},1000);
then php
$sql = "SELECT count(*) as count FROM i_case";
$qry = pg_query($connection, $sql);
$row = pg_fetch_assoc($qry);
echo $row['count'];
Hello everyone so I have partly working code. However I also have issues with it. But let me start off to tell you what I am trying to achieve... On my site I have a login facility which sends all users to a home page once and only if the user is logged in. I would like to display who else is logged in on my page showing there usernames in a list.
My codes current ability...
Okay so i can code it to add the users on joining the site to a database and also then display each user on that database into a div which is great as it displays everyone online...
Where the problem stands...
However, when a user leaves the page there username needs to be deleted from the online user database. In the past I would simply do this with a on window close option in java. But due to Google safari and Firefox no longer supporting this option I am forced to find another way of doing it.
What the code bellow does...
So the code bellow loads an interval so after so much time it will repeat the code within it. The code first adds the user to the database, it then displays the user in a list on the site and then it deletes the user from the database just in case they are to then go offline.
Where the problem stands...
This all being very well for one user, but once a second user gets involved there intervals fall at a different time. So I have deleted the user from the database after it shows the list but then it means the second user displays the database and the first user isn't in it as they are deleted... This also causes a problem should a user go offline half way though the function happening, then it leaves them in the database and doesn't get around to deleting them out of the database.
The following is the java code...
$(document).ready(function() {
var user_name = "<?php print $username ?>";
setInterval(function() {
$.post('onlineusers.php', { name: user_name, action:"joined" });
$.post("onlineusers.php", { action2: "list" }, function(data){
$('#listusers').html(data);
});
$.post("onlineusers.php", { nameleft: user_name, action3:"left" }, function(data){
$('#errorrreport').html(data);
});
}, 5000);
}):
Now there is the PHP document code
//------------User joined page put into database --------
if( $_REQUEST["name"])
{
$user_name = $_REQUEST['name'];
};
if( $_REQUEST["action"])
{
$action = $_REQUEST['action'];
};
if ($action == 'joined') {
user_joined($user_name);
};
//-----------Listing online users within page -------------
if( $_REQUEST["action2"])
{
$action2 = $_REQUEST['action2'];
};
if($action2 == 'list') {
foreach (user_list() as $user){
echo $user . "<br />";
};
};
//------------ User left delete from the database ------------
if( $_REQUEST["nameleft"])
{
$user_nameleft = $_REQUEST['nameleft'];
};
if( $_REQUEST["action3"]){
$action3 = $_REQUEST['action3'];
};
if($action3 == 'left') {
user_left($user_nameleft);
};
//------ Functions what to do... --------
function user_joined($user_name) {
$user_name = mysql_real_escape_string(htmlentities($user_name));
mysql_query("INSERT INTO users (user_name)VALUES('$user_name')") or die("this didn't happen");
}
function user_left($user_nameleft) {
$user_name = mysql_real_escape_string(($user_nameleft));
$query = mysql_query("DELETE FROM users WHERE user_name = '$user_nameleft'")or die("failed to delete from table");
}
function user_list() {
$user_list = array();
$users_query = mysql_query("SELECT user_name FROM users") or die ("Unable to collect userlist");
while ($users_row = mysql_fetch_assoc($users_query)){
$user_list[] = $users_row['user_name'];
}
return $user_list;
}
The above code
Sorry it is slightly messy due to my recoding of it so many times in order to get it to work.
I would appreciate it if anyone could give me any help towards getting this to work. Now if it's not just simple off the code from above I can add the user to the online user database on entrance to the page and get it to list who is online frequently from listing the users on the database.
The real issue and where i am asking for your help with please...
However, if you have any idea on the code for the following that would be great... The user leaving the page is where the problem comes up. I need some method of checking the user is still active and if they are not then deleting them from the database so when the list then refreshes the user is no longer on the list. Such as pinging something until it ends up with no response and deletes the user from the database.
As my current code has problems with multiple users and synchronization of the interval function it needs to take that into account different users will see the list refresh at different times.
P.S. I have also looked at using $SESSION however i am still not sure on how to make this work with checking for offline users and then deleting them from the database this might be a method of doing it.
Thank you, I hope there is enough information to go on.
I've taken a different approach:
JS:
Loop of 5 seconds, AJAX requests onlinenow.php and displays the returned html in the online users box - This is mostly copied and pasted from W3C with the URL changed.
setInterval("getOnline()",5000);
function getOnline()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("onlineNow").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","http://www.path.com/to/onlinenow.php",true);
xmlhttp.send();
}
PHP:
Takes user/ip/identifier and stores/updates that + unix timestamp in the DB
Returns a list of all rows with unix timestamp in the past 10 minutes
<?php
header('Access-Control-Allow-Origin: *');//Pretty sure this enables cross domain AJAX
$session = $_SERVER['REMOTE_ADDR'];
$time=time();
$time_check=$time-60; //SET TIME 10 Minute
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="pass"; // Mysql password
$db_name="custom"; // Database name
$tbl_name="table"; // Table name
// Connect to server and select databse
mysql_connect("$host", "$username", "$password")or die("cannot connect to server");
mysql_select_db("$db_name")or die("cannot select DB");
// Check if user is already in the DB
$sql="SELECT * FROM $tbl_name WHERE session='$session'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count=="0"){
//User is not in the DB, lets add them
$sql1="INSERT INTO $tbl_name(session, time, ip)VALUES('$session', '$time', '".$_SERVER['REMOTE_ADDR']."')";
$result1=mysql_query($sql1);
}
//Update this user's entry
else {
//User is in the DB, Update their entry
$sql2="UPDATE $tbl_name SET time='$time' WHERE session = '$session'";
$result2=mysql_query($sql2);
}
//Done updating info, time to get the user list
// if over 10 minute, delete session - Could just get all in past 10 mins instead
$sql4="DELETE FROM $tbl_name WHERE time<$time_check";
$result4=mysql_query($sql4);
//Get total users (Could get a list of names if you preferred and store the info)
$sql3="SELECT * FROM $tbl_name";
$result3=mysql_query($sql3);
$count_user_online=mysql_num_rows($result3);
if ($count_user_online == 1) {
$plur = "";
}
else {
$plur = "s";
}
echo " $count_user_online user".$plur." online now ";
// Close connection
mysql_close();
?>
I've used this logic several times with and without usernames shown (sometimes just a number).
The code, of course, could be improved, but the basic principle is a fairly good solution.
You could try instead of deleting to include a timestamp (server based) when inserting.
Then have the javascript code insert/update every minute or so.
Then your query of who's on is simply which rows have a recent timestamp (like the last 65 seconds)
You'll have to clear out old rows in the table eventually, of course, unless you want a log of everyone who was ever on and when.
When my application publishes a message on the user's wall (through permits streampublish) I want you to get a notification to the user in red. How can I do?
If I can not there are alternative solutions? . For example, I thought to send a private message to you through my application. how can I do?
Showing Notifications
You can do this by using a db column that holds the notification status lets say when the notification_status = 0 the user didn't see the notification yet
when the notification_status = 1
then you send request to server every mount of time lets say 15 seconds and then test weather there is notification_status = 0 or not if yes show a div and send the number of notifications in it
setInterval(function() {
$.post("notifications_tester.php",function(data){
if(data != 0 )
{
$('#notifications_div').show().html(data);
}
else
{
$('#notifications_div').hide().html("");
}
});
}, 15000);
sample what would be in notifications_test.php
session_start();
//connect to the DB
$user_id = $_SESSION['user_id'];
$q = mysql_query("SELECT * FROM posts WHERE user_id = '".$user_id."' AND notification_status = 0");
echo mysql_num_rows($q);