I want to do something when the beforeunload is canceled - javascript

my english is not good. sorry.
I want developing a CMS with php. And I want to change the on_desk database column to 1 when the post edit page is opened and the on_desk column to be 0 when exiting same page
By doing this while you are in the Edit Post window tab. I want to prevent the same page from opening in a new window.
I used the following solution. But sometimes it doesn't work well.
For example, when I cancel the dialog, it does not work well
Do you have another solution? For example, the way not to use beforeunload.
Javascript|jQuery:
function clearDesk(){
$.post('clearOnDesk.php',{
"id":parseInt($('body').attr('data-pageId')),
}, function(){
$('body').attr('data-desk',1)
});
}
function setDesk(){
$.post('setOnDesk.php',{
"id":parseInt($('body').attr('data-pageId')),
}, function(){
$('body').attr('data-desk',2)
});
}
setDesk();
const beforLoadFunc = function beforLoadFunc () {
clearDesk();
if(parseInt($('body').attr('data-desk')) == 1){
setTimeout(() => {
window.addEventListener('mousemove', (e) => {
setDesk();
});
}, 1000);
}
}
window.addEventListener('beforeunload', function onBeforeUnload(e) {
setTimeout(beforLoadFunc, 500);
const dialogText = 'are you sure?';
e.returnValue = dialogText;
return dialogText;
});
clearOnDesk.php
if($_POST)
{
$id = (int)$this->post('id');
if($id && $id != '')
{
$w['id'] = $id;
} else die("die!");
$d['on_desk'] = 1;
$this->db->update('post',$d,$w,["i","i"]);
//update on_desk to 0 for (post row) in database by (pageId).
//by PHP Prepared Statements
}
setOnDesk.php
if($_POST)
{
$id = (int)$this->post('id');
if($id && $id != '')
{
$w['id'] = $id;
} else die("die!");
$d['on_desk'] = 2;
$this->db->update('post',$d,$w,["i","i"]);
// update on_desk to 1 for (poster row) in database by (pageId).
//by PHP Prepared Statements
}

Related

JS Event Listener check on PHP session infinitely

I want my page to consistently check if the user session is still active.
if using event listener. My concern is that php file execution time is limited. is there way to set php execution to infinite? or is there a better way of doing this?
JS:
$(document).ready(function() {
var loginSource = new EventSource("/structure/ajax/check_login_session.php");
loginSource.addEventListener("login-verification", function(e) {
var response = JSON.parse(e.data);
if (data.login_failed) {
login_fail_redirect();
}
});
})
php
function send_response() {
if (empty($_SESSION['user_info']) || empty($_SESSION['user_info']['active'])) {
$response = array("status" => "failed", "login_failed" => 1);
} else {
$response = array("status" => "success", "login_failed" => 0);
}
echo "event: login-verification\n";
echo 'data: '.json_encode($response);
echo "\n\n";
flush();
}
while (true) {
send_response();
sleep(2);
}
Use a javascript setInterval instead. It will send timed requests to the backend to check if the session is active or not.
$(document).ready(function() {
setInterval(function {
var loginSource = new EventSource("/structure/ajax/check_login_session.php");
loginSource.addEventListener("login-verification", function(e) {
var response = JSON.parse(e.data);
if (data.login_failed) {
login_fail_redirect();
}
});
},1000); //time in ms
})
Then replace this code from your backend:
while (true) {
send_response();
sleep(2);
}
to
send_response();

Form submited two times (ajax with jquery)

i have a simple form: when i submit it without javascript/jquery, it works fine, i have only one insertion in my data base, everything works fine.
I wrote some jquery to have result in ajax above the input button, red message if there was an error, green if the insertion was done successfully. I also display a small gif loader.
I don't understand why when i use this jquery, two loaders appear at the same time and two insertions are done in my database.
I reapeat that when i comment the javascript, it works fine, i'm totally sure that my php is ok.
$('#addCtg').submit(function () {
var action = $(this).attr('action');
var name = $('#name').val() ;
$('.messages').slideUp('800', function() {
$('#addCtg input[type="submit"]').hide().after('<img src="spin.gif" class="loader">');
$.post(action, {
name: name
}, function (data) {
$('.messages').html(data);
$('.messages').slideDown('slow');
$('.loader').fadeOut();
$('#addCtg input[type="submit"]').fadeIn();
});
});
return false;
});
I really don't understand why it doesn't work, because i use the 'return false' to change the basic behaviour of the submit button
Basic php just in case:
<?php
require_once('Category.class.php');
if (isset($_POST['name'])) {
$name = $_POST['name'] ;
if ($name == "") {
echo '<div class="error">You have to find a name for your category !</div>' ;
exit();
} else {
Category::addCategory($name) ;
echo '<div class="succes">Succes :) !</div>' ;
exit();
}
} else {
echo '<div class="error">An error has occur: name not set !</div>';
exit();
}
And finnaly my function in php to add in the database, basic stuff
public static function addCategory($name) {
$request = myPDO::getInstance()->prepare(<<<SQL
INSERT INTO category (idCtg, name)
VALUES (NULL, :name)
SQL
);
$r = $request->execute(array(':name' => $name));
if ($r) {
return true ;
} else {
return false ;
}
}
I rarely ask for help, but this time i'm really stuck, Thank you in advance
You're calling: $('.messages') - I bet you have 2 elements with the class messages. Then they will both post to your server.
One possible reason could be because you are using button or submit to post ajax request.
Try this,
$('#addCtg').submit(function (e) {
e.preventDefault();
var action = $(this).attr('action');
var name = $('#name').val() ;
$('.messages').slideUp('800', function() {
$('#addCtg input[type="submit"]').hide().after('<img src="spin.gif" class="loader">');
$.post(action, {
name: name
}, function (data) {
$('.messages').html(data);
$('.messages').slideDown('slow');
$('.loader').fadeOut();
$('#addCtg input[type="submit"]').fadeIn();
});
});
return false;
});

How to avoid the session timeout in non-login situation php?

I have set 2 min for session timeout and if it occurred the page
will redirect to a session timeout page.
However, I have some pages that could be browsed without login.
In these pages, if I leave it more than 2 min, pop out will appear asking user to log in again. User will go back to click it and it will redirect to session timeout page.
Could anyone teach me, how to get rid of this such that the pages be browsed without login should not occur session time?
ajax.js
window.onload = init;
var interval;
function init() {
interval = setInterval(trackLogin, 1000);
}
function trackLogin() {
var xmlReq = false;
try {
xmlReq = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlReq = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
xmlReq = false;
}
}
if (!xmlReq && typeof XMLHttpRequest != 'undefined') {
xmlReq = new XMLHttpRequest();
}
xmlReq.open('get', 'check.php', true);
xmlReq.setRequestHeader("Connection", "close");
xmlReq.send(null);
xmlReq.onreadystatechange = function() {
if (xmlReq.readyState == 4 && xmlReq.status == 200) {
if (xmlReq.responseText == 1) {
clearInterval(interval);
alert('You have been logged out. You will now be redirected to home page.');
document.location.href = "index.php";
}
}
}
}
firstSession
<?php
// session_start ();
if (! isset ( $_SESSION ["isLoggedIn"] ) || ! ($_SESSION ['isLoggedIn'])) {
// code for authentication comes here
// ASSUME USER IS VALID
$_SESSION ['isLoggedIn'] = true;
$_SESSION ['timeOut'] = 120;
$logged = time ();
$_SESSION ['loggedAt'] = $logged;
// showLoggedIn ();
} else {
require 'timeCheck.php';
$hasSessionExpired = checkIfTimedOut ();
if ($hasSessionExpired) {
session_unset ();
header ( "Location:index.php" );
exit ();
} else {
$_SESSION ['loggedAt'] = time ();
}
}
?>
footer.php
<?php include ('includes/firstSession.php'); ?>
<footer class="main">
<div class="wrapper container">
<div class="copyright">All Rights Reserved
</div>
<div class="logo"><img src="images/logo.png"></div>
</footer>
</div>
draft ajax.js
window.onload = init;
var interval;
function init() {
interval = setInterval(trackLogin, 1000);
}
function trackLogin() {
var xmlReq = false;
try {
xmlReq = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlReq = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
xmlReq = false;
}
}
if (!xmlReq && typeof XMLHttpRequest != 'undefined') {
xmlReq = new XMLHttpRequest();
}
xmlReq.open('get', 'check.php', true);
xmlReq.setRequestHeader("Connection", "close");
xmlReq.send(null);
xmlReq.onreadystatechange = function() {
if (xmlReq.readyState == 4 && xmlReq.status == 200) {
return json_encode(array(
'role' => $_SESSION['role'], //assuming something like guest/logged-in
'user_id' => $_SESSION['user_id']
));
var obj = xmlReq.responseText;
var jsonObj = JSON.parse(obj);
//now we can make a comparison against our keys 'role' and 'user_id'
if(jsonObj['role'] == 'guest'){
//guest role, do something here
} else if (jsonObj['role'] == 'logged-in') {
alert('You have been logged out. You will now be redirected to home page.');
document.location.href = "index.php";
//do something else for logged in users
}
I think since you have a session that is persistent whether logged in or not, you need to base your action on the username (however that is set). See if this is what you are trying to do. I have notated for clarity:
myfunctions.php
<?php
// return a session set on not set OR false if set
function is_loggedin()
{
return (!empty($_SESSION["isLoggedIn"]));
}
// Check if username is set (not sure how your usernames are stored in your session
// but that is what you want to check here
function user_set()
{
return (!empty($_SESSION["username"]));
}
// Do your set time function
function set_time_out($timeout = 120)
{
$_SESSION['isLoggedIn'] = true;
$_SESSION['timeOut'] = (is_numeric($timeout))? $timeout : 120;
$_SESSION['loggedAt'] = time();
}
function process_timeout($supRed = false)
{
// If a user has NOT already been poking around your site
if(!is_loggedin()) {
// Set the timeout
set_time_out();
return 0;
}
else {
// If a navigating user is logged in
if(user_set()) {
// Check for expire time
require('timeCheck.php');
// If they have been timed out
if(checkIfTimedOut()) {
if(!$supRed) {
// destroy the session and forward to login (or wherever)
session_destroy();
header("Location:index.php" );
exit();
}
return 1;
}
}
// Set the logged time by default
$_SESSION['loggedAt'] = time();
}
return 0;
}
header.php
<?php
include_once("includes/firstSession.php");
include_once("includes/myfunctions.php");
process_timeout();
?><!DOCTYPE html>
...etc
check.php
<?php
include_once("includes/firstSession.php");
include_once("includes/myfunctions.php");
echo process_timeout(true);
EDIT:
This is the entire script, both js and php.
// return a session set on not set OR false if set
function is_loggedin()
{
return (!empty($_SESSION["isLoggedIn"]));
}
// Check if username is set (not sure how your usernames are stored in your session
// but that is what you want to check here
function user_set()
{
return (!empty($_SESSION["username"]));
}
// Do your set time function
function set_time_out($timeout = 120)
{
$_SESSION['isLoggedIn'] = true;
$_SESSION['timeOut'] = (is_numeric($timeout))? $timeout : 120;
$_SESSION['loggedAt'] = time();
}
function checkIfTimedOut()
{
if(!empty($_SESSION['loggedAt'])) {
$active = ($_SESSION['loggedAt'] + strtotime("120 seconds"));
$now = time();
return (($active - $now) > 0);
}
return true;
}
function process_timeout($supRed = false)
{
// If a user has NOT already been poking around your site
if(!is_loggedin()) {
// Set the timeout
set_time_out();
return 0;
}
else {
// If a navigating user is logged in
if(user_set()) {
// Check for expire time
// If they have been timed out
if(checkIfTimedOut()) {
// destroy the session
session_destroy();
if(!$supRed) {
// Forward to login (or wherever)
header("Location:index.php" );
exit();
}
return 1;
}
}
// Set the logged time by default
$_SESSION['loggedAt'] = time();
}
return 0;
}
check.php:
// Include the functions here
if(!empty($_POST['getPost'])) {
echo json_encode(array("redirect"=>process_timeout(true),"sess"=>$_SESSION));
exit;
}
CALLING PAGE:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script>
function init()
{
interval = setInterval(trackLogin, 2000);
}
function trackLogin()
{
$.ajax({
url: '/check.php',
data: { getPost: true },
type: 'post',
success: function(response) {
var instr = JSON.parse(response);
console.log(response);
if(instr.redirect == 1) {
clearInterval(interval);
alert('You have been logged out. You will now be redirected to home page.');
document.location.href = "index.php";
}
}
});
}
$(document).ready(function() {
var interval;
init();
});
</script>
EDITED

Javascript settimeout doesn't close the popup

Hi guys I'm using this function to open a popup and close it after 3 seconds. The popup opens successfully, but, the settimeout function doesn't works and eventually doesn't close the opened popup.
What am I doing wrong here?
<script type="text/javascript">
function popUp(id,entry,escape)
{
popupWindow = window.open('process_concur.php?id='+id+'&entry='+entry+'&escape='+escape,'Concur','resizable=yes,scrollbars=yes,width=250,height=250');
popupWindow.focus();
setTimeout(function () { popupWindow.close();}, 3000);
}
//reload the current window when the popup is closed.
function popUpClosed() {
window.location.reload();
}
</script>
The popup page which opens (Code)
<?php
include 'classes/class.user.php';
$userMain = new user();
//get parameters
$id = isset($_GET['id']) ? $_GET['id'] : '';
$entry = isset($_GET['entry']) ? $_GET['entry'] : '';
$escape = isset($_GET['escape']) ? $_GET['escape'] : '';
//now, $escape is sha1 and $entry is base64 encoded..decode entry and check if sha1 of decoded entry matches escape
$dentry = base64_decode($entry);
if(sha1($dentry)==$escape)
{
//process concur
if($userMain->reviewExists($id))
{
if($userMain->increaseConcur($id))
{
echo "Done";
exit();
}
}
else
{
//review doesnt no exist
echo "Some problems occured at id doesn't exist";
}
}
else
{
echo "Some problems occured dentry";
}
?>
<script>
window.onunload = function() {
if (window.opener && !window.opener.closed) {
window.opener.popUpClosed();
}
};
</script>
Your code looks correct. Ensure nothing else is interfering with the process.
Also, the popUpClosed() function should be invoked after the window is sent the close signal.
<script type="text/javascript">
function popUp(id,entry,escape)
{
var popupWindow = window.open('process_concur.php?id='+id+'&entry='+entry+'&escape='+escape,'Concur','resizable=yes,scrollbars=yes,width=250,height=250');
popupWindow.focus();
setTimeout(function () { popupWindow.close(); popUpClosed();}, 3000);
}
//reload the current window when the popup is closed.
function popUpClosed() {
window.location.reload();
}
popUp();
</script>

php session_id change on header redirect

What I am trying to do is increment the value inside the COOKIE in every redirect... but every time I check if the cookie exists it doesn't.
I try to do it with a SESSION also, but the session_id changes in each redirect (I am guessing that the redirect create a new session for some reason )
This is my code
<script language="javascript">
var popexurl = "<?php echo $PopExitUrl ?>";
if(popexurl != ""){
(function() {
setTimeout(function() {
<?php
if (isset($_COOKIE["count"]))
{
//cheak user refreshes
$cookie = (int)++$_COOKIE['count'];
setcookie("count", $cookie, time()+3600);
}
else
{
setcookie("count", 1, time()+3600);
$cookie=0;
}
?>
var __redirect_to = '<?php echo $PopExitUrl; ?>';//
var _tags = ['button', 'input', 'a'], _els, _i, _i2;
for(_i in _tags) {
_els = document.getElementsByTagName(_tags[_i]);
for(_i2 in _els) {
if((_tags[_i] == 'input' && _els[_i2].type != 'button' && _els[_i2].type != 'submit' && _els[_i2].type != 'image') || _els[_i2].target == '_blank') continue;
_els[_i2].onclick = function() {window.onbeforeunload = function(){};}
}
}
window.onbeforeunload = function() {
window.scrollTo(0,0);
document.getElementById('ExitBackDiv').style.display = 'block';
document.getElementById('ExitDiv').style.display = 'block';
setTimeout(function() {
window.onbeforeunload = function() {};
setTimeout(function()
{
window.location = __redirect_to;
}, 500);
},5);
<?php
if ($PopupMessage == ""){
$PopupMessage= "\\n**********************\\nWAIT! WAIT! WAIT! WAIT!\\n\\n**********************\\n\\nDont Miss This LAST CHANCE to become Financially Secure and CHANGE YOUR Lifestyle!!!\\n\\n...Click STAY ON THIS PAGE to activate your LIMITED time offer!";}
?>
var popmsg = "<?php echo $PopupMessage ?>";
if (navigator.userAgent.indexOf("Firefox")!=-1)
{
//setTimeout('window.location="'+__redirect_to+'"', 10);
window.alert(popmsg);
return popmsg;
}
else
{
return popmsg;
}
}
}, 500);
})();
}
</script>
session_start(); creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.
PHP: session_start()

Categories

Resources