Delete an entry from db on PHP page exit - php

I have a php page in which a user tries to find online people.
There a search button, clicking on which, an entry is made for the current user in the database and the control goes inside a loop, where every 5 secs a search is made in the database to find if a new entry has been made, if an entry is found then the details of the partner is shown to him.
I want that if the user exits or navigates away from the page before a partner is being found, then his entry must be deleted from the db.
I am trying to store the 'id' created against the user inside a session variable, make an ajax call and delete the entry, but somehow this concept is not working.The data is not getting deleted. Is this because of the loop which is still finding the user or something else, m not able to get it.
Can anyone tell me what is going wrong with my approach ?
A code snippet that I am using is hereby
window.onbeforeunload = function() {
funcDeleteonexit();
return "Are you sure you want to navigate away?";
}
function funcDeleteonexit(){
$.get("functions.php",{
data:"delete"
},function(data,status){
});
}
Inside my functions.php, I have
if($_GET){
if ($_GET['data']=="delete"){
echo deletefromDb();
}
}
function deletefromDb() {
$mysqli = new mysqli("localhost", "root", "", "test");
/* check connection */
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$currentid = (int)$_SESSION['currentId'];
$query1 = "delete from test where id =". $currentid;
$mysqli->query($query1);
$mysqli->close();
return $currentid;
}

If you want something done when someone exits the page, this will in most cases give you trouble if you want a specific event to be fired then. There will be cases a browser cannot fire the event (p.e. client crash etc.).
Therefore I'd suggest a different approach. Control this from the server side, and don't rely on the users browser or input.
Firstly, you can poll your data while regularly firing Ajax events from the browser. You've not stated this, but I think you do something like this:
function yourrequest(){
$.ajax({
type: "GET",
url: "your/php/script.php",
success: function(data){
// do something, p.e. update a div
}
});
};
setInterval(yourrequest, 5000);
(Please don't tear this code sample apart, its just to show the basics).
On the server side, you already have the users id somewhere in your database. Add a timestamp field to this table (call it last_request or something like that). Everytime you send some data to the client, check if there are users with a last_request below your desired threshold, and delete those ids. No need to wait for a specific event then.
This needn't be done exactly there, you can also do something different, p.e. a cleanup job cronned every 5 minutes or so which does this seperately to not disturb the users request at all.

I'm suggesting that browser just not sending ajax, or interupting it.
So try to make your AJAX request synchronous. For JQuery seems to be set async parameter to false
$.get("functions.php",{
data:"delete",
async : false
},function(data,status){
});

Related

When I exit a screen, I should be asked: “Do you want to save?” codeigniter

I want to do something like this: If I am viewing a record and edit it or add a new record and then exit that screen, I should be asked, “Do you want to save?”
How can I develop this thing in php? I haven't done this type of development before..
Any suggestions?
use jquery onbeforeunload function it will be execute when page refresh or
closing browser tab or closing browser .
$(window).on('beforeunload', function(){
return 'Are you sure you want to leave?';
});
You need to look for changes in javascript. Make a global variable, lets call it changed . Set it to false on page load. Whenever record is edited make it true and whenever it is saved , set it to false. When the user is closing his tab, again which needs to be detected in JS, look for changed variable. If it is true give him a prompt else he can close without any issues.
You will need to javascipt/jquery to listen for the unload event on the window.
I believe you could do something along the lines of:
<script>
function saveAlert() {
var confirm = confirm('You haven\'t saved your form! Do you want to save?');
if (confirm) {
$('form').submit();
}
return confirm;
}
$(function() {
var formSaved = <?=($formSaved) ? 'true' : 'false'?>;
if (!formSaved) {
$( window ).unload(saveAlert());
}
});
All you will need to do is pass a boolean in the $formSaved variable to determine whether the alert needs to be shown or not.
If you wanted to attempt a solution to this question in PHP, you would need to use AJAX to store field data in the database on change/update of fields, without committing the change to the table - you could store it in a cookie or session variable, or in an 'unsaved_records' table of some sort.
If your user navigates to an off-site domain there's nothing you can do in PHP but if they come back to your site, you can alert "you have unsaved data, do you want to continue where you left off?".
You could also wait till they return to the page where they had unsaved data, and restore it to the state it was in, as though they had never left. This would require some careful planning, but it's possible.
Only client side scripting can pause the window or tab being directed to a new location, as is evident in the other answers here.

show notification with php when a specific data is changed in a database

I want to notify a person a count of the jobs available in a table in my database. In a table I have a list of 8 jobs and they have their avilability. I've done the count with a PHP query with SELECT COUNT(*) AS jobs... and created this ajax script which shows the count with an interval.
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function() {
$('#divToRefresh').load('notification.php'); //this contains the query
}, 30000);
});
However, I am not sure how I can make it so when the user sees the notifcation alert, they will close it and it doesn't appear again until there's a new available job.
I can't find anything on the good ol google either.
Your jQuery function is running in 30 seconds intervals polling data from server. notification.php returns pre-rendered HTML containing (I assume among other things) the number of jobs available.
Check the number of available jobs and show notification based on that:
setInterval(function() {
var oldNumberOfJobs = newNumberOfJobs = 0;
$('#divToRefresh').load('notification.php'); //this contains the query
newNumberOfJobs = $('#divWithJobsCount').text;
if (newNumberOfJobs > oldNumberOfJobs) {
// show notification to the user
}
oldNumberOfJobs = newNumberOfJobs;
}, 30000);
To be more specific (showing/hiding notifications), I need to see your HTML.
This solution feels bulky. The whole pre-rendered HTML is being reloaded again and again. A nicer approach would be to only return the number of jobs available and only update that number using jQuery.
Also, it might be a good idea to return the latest job_id as well as the total number of jobs available. This way, you could check if the latest job_id that is already stored in the front end matches the newly received job_id. And only if they don't match you would update the counter and show new notification.
update
Here is a jsfiddle.js which covers your case. Jobs counter is simulated with current number of minutes. The function checks every 15 seconds if the number of minutes has changed. Once it happens, an alert notification is shown (but only if the old one was closed).
setInterval in jsfiddle is written using a mock object so that it is testable in the browser without AJAX requests. In your code use the following form:
setInterval(function() {
$.get('notification.php', checkJobsCounter); // returns jobs count in plain text
}, 30000);
Well you need to make an AJAX call and the response of it should be the number of new notifications. Now check if num>0 then just do $("#notification").fadeIn(); which is a by default hidden div having text You have new notification (or whatever) and a close button.
$(doument).ready(function(){
setInterval(function(){
$.get("notification.php", function(data){
if(data>0)
{
$("#div").fadeIn();
}
});
},1000);
});
Once user closes this you can create a cookie in the browser of the user and then check if cookie is set dont make ajax request, This was you dont have to update the db and every user will be able to see the notification.

Warn user when new data is inserted on database

I don't know how to search about this so I'm kinda lost (the two topics I saw here were closed).
I have a news website and I want to warn the user when a new data is inserted on the database. I want to do that like here on StackOverflow where we are warned without reloading the page or like in facebook where you are warned about new messages/notifications without reloading.
Which is the best way to do that? Is it some kind of listener with a timeout that is constantly checking the database? It doesn't sounds efficient...
Thanks in advance.
You need javascript ajax and json and callback function to check constantly. It can be done by push services but PHP is bad with that and you need websockest, etc. facebook uses timeout calls. not sure for the stackoverflow
refreshInterval = 500
refreshTimeout = setTimeout( getNotificationCounts, refreshInterval );
function getNotifications() {
$.ajax({
url : 'path_to_your_php',
type : 'POST',
data: //put for exampel user_id but it cvan be handled by sesion as well
dataType : 'json',
success : function(data) {
alert('You have'+ data.total +' new messages')
refreshTimeout = setTimeout( getNotificationCounts, refreshInterval ); //this will check every half of second
}
});
}
then in PHP, for example you have a flag in database with which you check if data is new to teh databse. Mind the formatting and to proper sql escape
$result=mysql_query("SELECT count(*) as total from myTable where user_id=$_POST['user_id'] AND is_read=0");
//note instad of $_POST you can use session if users are logged in, or however you are handling it
$data=mysql_fetch_assoc($result);
echo json_encode($data)
;
After that you can create another ajax call that marks messages as read once user clicks on them. or opens a dialog listing or wahtever
mysql_query("UPDATE myTable WHERE user_id=$_POST['user_id'] SET is_read=1");

Upating mysql fields asynchronously with ajax when "Like" is clicked

The question is fairly simple. Whenever user clicks on "like" I want to use javascript to update the mysql database through ajax. I have tried all means bit have found nothing helpful. I know I will also need a server side script but the ajax is the main issue.
Here is the counter code I set up.
document.observe("dom:loaded", function()
{
$("likeForumLink").onclick=processForumLike;
});
function processForumLike(event)
{
var numberOfLikes=parseInt($("hiddenLikes").value);
numberOfLikes+=1;
$("hiddenLikes").value=numberOfLikes+"";
this.innerHTML="You liked this";
if(numberOfLikes==1)
{
$("numberOfLikes").innerHTML="("+numberOfLikes+" like)";
}
else
{
$("numberOfLikes").innerHTML="("+numberOfLikes+" likes)";
}
var likes=$("hiddenLikes").value;
new Ajax.Request("seeForum.php?id=$("subjectId").value", {
method:'get',
parameters:{hiddenLikes:likes},
onSuccess: ???? //Don't know
onComplete:??? //Don't know
on Failure:???? //Don't know
});
}
And then I can use my server side script as follows.
P.S. It lies in the same page "seeForum.php?subjectId=$("subjectId").value"
<?php if(isset($_GET["hiddenLikes"]))
{
$updateQuery="UPDATE `subject table` SET `likes`='".$_GET["hiddenLikes"]."' where `subjectId`='".$_REQUEST['subjectId']."' ";
$result=mysql_query($updateQuery);
checkConnect($result,"query of $updateQuery");
?>
Please help. All my work has come to a halt.
First of all, you shouldn't be using a GET request to update data, that should be a POST. And this:
"seeForum.php?id=$("subjectId").value"
doesn't do what you probably think it does. What it does do is cause a syntax error because it looks like "x" x "x" to the JavaScript interpreter and that's not JavaScript. I'm not sure which JavaScript library you're using (Prototype perhaps?) but I think you probably want to put all your parameters into parameters to avoid having to worry about URL encoding and things like. Furthermore, there's no reason to tell the server how many "likes" you already have and there is a good reason not to: someone might have "liked" the page while you're looking at some the number of likes you currently have will be wrong; so hiddenLikes isn't needed at all.
Something like this would be better on the JavaScript side:
new Ajax.Request("likeIt.php", {
method: 'post',
parameters: { id: $('subjectId').value },
onSuccess: function(transport) {
// Update the "likes" label with something like this,
// I'm not that familiar with Prototype though so I'm
// guessing.
$('likes_label').update(transport.responseText);
},
onComplete: ???? // The function to call when it has finished.
onFailure: ???? // The function to call when it doesn't work.
});
And then, in the PHP, just send a simple UPDATE to the database to increment the number of likes in likeIt.php, something like this:
<?php
# Perform whatever authentication you need...
if(isset($_POST["id"])) {
# Set up your database connection and then...
$result = mysql_query("UPDATE `subject_table` SET `likes` = `likes` + 1 WHERE `subjectId` = '" . mysql_real_escape_string($_POST["id"]) . "'");
# Check $result and send some data back to the client (if desired), if
# you send something back then the onComplete, onFailure, and onSuccess
# JavaScript functions would be responsible for doing something with it.
}
# Send back the updated number of "likes" as text/plain.
?>
Well thinking it through, if the user clicks on like, all you really want to do is increment the like counter in the page itself. You can do this in the onComplete: function(){ increment the like counter }. If some kind of error does occur, i don't think you would want to display it to the user, depends on how you want to handle that part, many ways to do it, you could log the error.

What's the best way to return stuff from a PHP function, and simultaneously trigger a jQuery action?

So the title is a tad ambiguous, but I'll try and give an example. Basically, I have an 'awards' system (similar to that of StackOverflow's badges) in my PHP/CodeIgniter site, and I want, as soon as an award is earned, a notification to appear to the user.
Now I'm happy to have this appear on the next page load, but, ideally I'd like it to appear as soon as the award is transactioned since my site is mostly Ajax-powered and there may not be page reloads very often.
The way the system works currently, is:
1) If the user does something to trigger the earning of an award, CodeIgniter does this:
$params['user_id'] = $this->tank_auth->get_user_id();
$params['award_id'] = 1; // (I have a database table with different awards in)
$this->awards->award($params);
2) My custom library, $this->awards, runs the award function:
function award($params)
{
$sql = $this->ci->db->query("INSERT INTO users_awards (user_id, award_id)
VALUES ('".$params['user_id']."','".$params['award_id']."')
ON DUPLICATE KEY UPDATE duplicate=duplicate+1");
$awardinfo = $this->ci->db->query("SELECT * FROM awards WHERE id = ".$params['award_id']);
// If it's the 'first time' the user has gotten the award (e.g. they've earnt it)
if ($awardinfo->row('duplicate') == 0) {
$params['title'] = $awardinfo->row('title');
$params['description'] = $awardinfo->row('description');
$params['iconpath'] = $awardinfo->row('iconpath');
$params['percentage'] = $awardinfo->row('percentage');
return $params;
}
}
So, it awards the user (and if they've earnt it twice, updates a useless duplicate field by one), then checks if it's the first time they've earnt it (so it can alert them of the award). If so, it gets the variables (title of the award, the award description, the path to an icon to display for the award, and finally the percentage of users who have also got this award) and returns them as an array.
So... that's that. Now I'd like to know, what's the best way to do this? Currently my Award-giving bit is called from a controller, but I guess if I want this to trigger via Ajax, then the code should be placed in a View file...?
To sum it up: I need the returned award data to appear without a page refresh. What's the best way of doing this? (I'm already using jQuery on my page).
Thanks very much everybody!
Jack
You need to implement a system of push notification. There are a couple of ways of doing this. You could simply poll for changes:
setInterval(check_awards, 30000);
function check_awards() {
$.getJSON('/awards.php', function(result) {
...
});
}
Every 30 seconds this checks for new awards. If something new is required, the PHP script returns an appropriate JSON object as to the type of award and so on.
Another way is to use faux push notification:
$(function() {
check_awards();
});
function check_awards() {
$.ajax({
url: '/awards.php',
success: function(data) {
// update awards
},
complete: function() {
check_awards();
}
});
}
This is sometimes called long-polling. You need to change it so your PHP script doesn't end until there's something to return. Whenever the AJAX request returns (due to success or timeout or other error) you start the request again.
For a detailed example see How to show popup message like in stackoverflow.

Categories