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>
Related
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
}
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();
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
When user clicks the logout button from the main page, the cookies will be deleted and they will be redirected to window.location = url; . Even if user does not login, but instead clicks logout, they will still be redirected to window.location = url;. My codes are as below, I can't seem to logout even if I click the logout button and I will stay at the main page while being logged in. Can anyone tell what is wrong? I am new to JavaScript and I need help regarding this topic.
$('.logout-btn').click(function(e){
e.preventDefault();
if(isset($_COOKIE['REFERER']) && $_COOKIE['REFERER'] != '') {
window.location = url;
}
else {
$.post(outurl, function( data ) {
}).then(function(r){
$('#popup_ok, .x-close').bind( "click", function() {
window.location = url;
});
if(r.result == 1){
popup_msg('Failed', r.msg);
}
else{
popup_msg('Success', r.msg);
setTimeout(function(){
window.location = url;
},2000);
}
});
}
});
try this code this will execute when user close the tab or close the browser it will automatically destroy session and cookies stored
<body onbeforeunload='destroySession()'>
</body>
<script type='text/javascript'>
function destroySession()
{
$.ajax({
url: 'process/logout.php'
});
}
</script>
logout.php
<?php
session_start();
unset($_SESSION['id']);
header("location:../login.php");
?>
specify the path of your file at place of login.php
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()