Re-enabling the submit button after a timeout - php

The submit_pdf button saves up the information into the database and to avoid multiple clicks, i initially had disabled the submit button after one click, however now i would like to re enable the button after a timeout of 10 seconds. The part till where the submit button gets disabled is working fine, but if i try to add a delay of 10 seconds, it doesn't seem to work.It would be really helpful if you could help me out with this.
echo ' <script language="JavaScript" type="text/javascript">
//<![CDATA[
window.open(\'./index_pdf.php?'.$query_string.'\',\'Warehouse_ST\',\'location=no,menubar=no,resizable=yes,scrollbars=yes,status=yes,toolbar=no\');
id_form.submit_pdf.disabled=true;
window.alert("Data is stored in the database, Please do no click on Submit again without changing any information");
window.addEvent(\'domready''\',function()
{
var subber = $_REQUEST["submit_pdf"];
subber.addEvent( \'click' ,function() '
{
subber.set( \'value','Submitting...''\' ).disabled = true;
(function() { subber.disabled = false; subber.set(\'value','submit_pdf'\'); }).delay(10000); // how much time? 10 seconds
});
});
//]]>
</script>';

try using setTimeout()
define a function to enable the button, and then set a setTimeout():
function enableButton(){
$('#myButton').attr("disabled", false);
}
setTimeout(enableButton, 10000);
make sure to put the function name without quotes and without the "()"

I recommend to write JS code (aleation 's code is correct) and this PHP code.
PHP (store the time in a session var):
session_start(); //At the beginning of the PHP file
define("TIMEOUT", 10); //10 sec
//Check timeout
if (isset($_SESSION['expire'])) {
if ($_SESSION['expire']-time()>TIMEOUT) {
unset($_SESSION['expire']);
}
}
//Allow to do submit after 10 sec
if (!isset($_SESSION['expire'])) {
$_SESSION['expire']=time();
//Your submit code
}
This is because user can manipulate JavaScript and HTTP messages, but he/she can't manipulate php code.

Related

Ajax visit link without actually visiting link

I've got a basic like button concept on my site that visits url.tld?action=love and adds +1 to the link's database column.
It's a hassle redirecting to another page all the time though. Is it possible to click the button, and send a request to the URL without actually redirecting to a new URL? Also maybe refresh the button afterwards only so that the count updates?
For a general idea of what my download button is this is in the header:
<?php require_once('phpcount.php'); ?>
<p class="hidden"><?php
$time = time();
for($i = 0; $i < 1; $i++)
{
PHPCount::AddHit("$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]", "127.0.0.1");
}
echo (time() - $time);
/*echo "PAGE1 NON: " . PHPCount::GetHits("page1") . "\nPAGE1 UNIQUE: " . PHPCount::GetHits("page1", true);
echo "\n\n" . PHPCount::GetHits("page2");
$ntot = PHPCount::GetTotalHits();
$utot = PHPcount::GetTotalHits(true);
echo "###$ntot!!!!$utot";*/?></p>
And this is an example of my "love" button.
Love <span class="count">'. PHPCount::GetHits("$package_get?action=love", true).'</span>
The reason I used this method is because people create pages, and I wanted the like button to work out of the box. When their page is first visited it adds their url to the database, and begins tallying unique hits.
This is basically adding a new link column called downloadlink?action=love, and tallying unique clicks.
use the following code. assgin id="btn_my_love" to that button and add this code to you page
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
//assign url to a variable
var my_url = <?php echo "https://alt.epicmc.us/download.php?link='.strip_tags($package_get).'?action=love"; ?>;
$(function(){
$("#btn_my_love").click(function(){
$.ajax({
url:my_url,
type:'GET',
success:function(data){
//comment the following result after testing
alert("Page visited");
},
error: function (request, status, error) {
alert(request.responseText);
}
});
//prevent button default action that is redirecting
return false;
});
});
</script>
Yes, it is possible. I am assuming you know what ajax is and how to use it, if not I am not going to give you the code because some simple reading on ajax as suggested by #Black0ut will show you how. But the basic steps are as follows:
Send ajax request to a PHP script that will update +1 vote to the database
In the PHP script, add +1 to the database and return some data to the ajax, maybe the new number of votes
Parse the return data in your JavaScript and update the button accordingly

Javascript countdown timer that stops when window is not in focus

Ok , I'm having trouble to solve this , I'm a php / C# web developer , and have no experience or knowledge in Javascript, I have to do just this one thing that needs Javascript:
When a certain page loads, a counter starts. The client must stay on this page for 20 seconds. after, I want to execute php code.
So there are 2 issues concerning me, first: how do I stop the counter, if client leaves the page (meaning the page is not in focus).
2) How can I execute php in javascript? , or call a php function from Javascript.
The code I have so far is this:
<html>
<head>
</head>
<body>
<div id='timer'>
<script type="text/javascript">
COUNTER_START = 20
function tick () {
if (document.getElementById ('counter').firstChild.data > 0) {
document.getElementById ('counter').firstChild.data = document.getElementById ('counter').firstChild.data - 1
setTimeout ('tick()', 1000)
} else {
document.getElementById ('counter').firstChild.data = 'done'
}
}
if (document.getElementById) onload = function () {
var t = document.createTextNode (COUNTER_START)
var p = document.createElement ('P')
p.appendChild (t)
p.setAttribute ('id', 'counter')
var body = document.getElementsByTagName ('BODY')[0]
var firstChild = body.getElementsByTagName ('*')[0]
body.insertBefore (p, firstChild)
tick()
}
</script>
</div>
</body>
</html>
and I also want the timer to start ticking when the client gets back on page
Thank you very much for ur help in advance
You could do this using jQuery.
Recycling an old Stackoverflow post, try this:
var window_focus;
var counter = 1000;
// on focus, set window_focus = true.
$(window).focus(function() {
window_focus = true;
});
// when the window loses focus, set window_focus to false
$(window).focusout(function() {
window_focus = false;
});
// this is set to the ('click' function, but you could start the interval/timer in a jQuery.ready function: http://api.jquery.com/ready/
$(document).one('click',function() {
// Run this function every second. Decrement counter if window_focus is true.
setInterval(function() {
$('body').append('Count: ' + counter + '<br>');
if(window_focus) { counter = counter-1; }
}, 1000);
});
Demo and old post
DEMO | Old So post
Update
Probably because the demo runs in 4 iframes, the $(window).focus bit only works on the iframe actually running the code (the bottom-right window).
jQuery
jQuery.com (How jQuery works) | Example (back to basics halfway down the page) | If you use the 2nd link, also read this
In regards to your first question about detecting if the window is out of focus, see this answer: Is there a way to detect if a browser window is not currently active?
It is possible, but only very new browsers support this so it may not be useful based on current browser support.
To trigger PHP code from Javascript, you would have to make an AJAX call to a server-side PHP script to invoke PHP since JS is client-side and PHP is server-side.

auto logout idle timeout using jquery php

I searched and find some examples to set idle timeout using jquery.
1 - Idle Timeout By Eric Hynds DEMO
2 - Idle Timer By paulirish
3 - Fire Event When User is Idle / DEMO HERE
4 - detect user is active or idle on web page
5 - Comet Long Polling with PHP and jQuery
6 - detacting idle timeout javascript
... And several other similar examples
Between these examples number 1 is better for i need because i need to auto logout user with any confirm alert after X minutes (logout.php or any url). but this method Not suitable for server. problem is : this jquery code send ping to any url : keepAlive.php in loop/pooling for request OK text . see firebug screen :
how to fix this ?
So, other examples only printed Idle/No Idle and not work with alert confirm and auto logout ( logout.php or any url ) now really better way to choose idle timeout using jquery/Php ?
Thanks
I use a meta refresh element in the head section to auto-direct users to the logout page after X number of seconds. Below will automatically send a user to the logout page after 20 minutes of staying on the same page:
<meta http-equiv="refresh" content = "1200; url=http://www.site.com/user/logout">
This works, is (mostly) supported cross-browser, does not rely on JavaScript being enabled and is pretty easy to implement.
If your site has users that stay on the same page for extended periods of time (with interaction taking place through JS, for instance), this solution will not work for you. It also does not allow any JS code to be run before redirection takes place.
Here is my approach that I applied to build a simple auto-logout feature with JavaScript and jQuery. This script was constructed for use with webpages that will automatically go to the logout page when mouse movement is not detected within 25 minutes.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
var idleMax = 25; // Logout after 25 minutes of IDLE
var idleTime = 0;
var idleInterval = setInterval("timerIncrement()", 60000); // 1 minute interval
$( "body" ).mousemove(function( event ) {
idleTime = 0; // reset to zero
});
// count minutes
function timerIncrement() {
idleTime = idleTime + 1;
if (idleTime > idleMax) {
window.location="LogOut.php";
}
}
</script>
<script>
var idleMax = 5; (5 min)
var idleTime = 0;
(function ($) {
$(document).ready(function () {
$('*').bind('mousemove keydown scroll', function () {
idleTime = 0;
var idleInterval = setInterval("timerIncrement()", 60000);
});
$("body").trigger("mousemove");
});
}) (jQuery)
function timerIncrement() {
idleTime = idleTime + 1;
if (idleTime > idleMax) {
window.location="Your LOGOUT or Riderct page url here";
}
}
</script>
Easy and simle
var autoLogoutTimer;
resetTimer();
$(document).on('mouseover mousedown touchstart click keydown mousewheel DDMouseScroll wheel scroll',document,function(e){
// console.log(e.type); // Uncomment this line to check which event is occured
resetTimer();
});
// resetTimer is used to reset logout (redirect to logout) time
function resetTimer(){
clearTimeout(autoLogoutTimer)
autoLogoutTimer = setTimeout(idleLogout,5000) // 1000 = 1 second
}
// idleLogout is used to Actual navigate to logout
function idleLogout(){
window.location.href = ''; // Here goes to your logout url
}

PHP No Reload Submit Value into MySQL Database (no return)

So what I am doing is trying to create a 'favorite' system. I want the user to click a button and the code on the page will submit a value into a MySQL Database. Does this need to the page need to reload if the only thing I am doing is submit and value. I am not pulling any information from the database on the button's click. Thank you:)
A great way to avoid the complexities of Ajax and cross-browser compatibility is to use Jquery!
In your non-reloading page, you can put this:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script text="text/javascript">
$(function() {
$('#button_id').click(function() { //in place of "button_id" you need to put your button's id
submitInformation("some information you want to send");
});
});
function submitInformation(data1)
{
$.post(
"handle.php", //this is the name and location of your php page
{
"input_var_one":data1,
}
);
}
</script>
and in your handler php page (in this case called "handle.php")
<?php
$inData1 = $_POST['input_var_one'];
//after your mysql_connect and mysql_select_db
$query = "INSERT INTO `yourtablename` VALUES ('var1 whatever you want', '$inData1')";
mysql_query($query);
?>
Jquery handles the Ajax request for you!
If you do not use AJAX, the information must be sent to the server in order to get to a mysql database table and processed by php and that surely requires page reload.
you can use:
<script type="text/javascript">
var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
function onthatbuttonclick(something)
{
window.xhr.open('GET', "somephp.php?click="+something, false);
window.xhr.send(null);
alert(window.xhr.responseText);
}
var somevar = "user 01";
</script>
<input type="button" onclick="onthatbuttonclick(somevar);" />
and in php:
<?php
// some query required code
// and yes... i does require some safety measures:
$val = mysql_real_escape_string($_GET['click']);
mysql_query("INSERT INTO `tabel` (`click`) VALUES ('".$val."')");
echo 'you cliked a button.';
?>
you should now see an alert box with the text: "you clicked a button.".

Force Logout users if users are inactive for a certain period of time

Assume that you are doing a banking application. If users are logged into your site, how to detect their inactivity and ask them to log out if they remain inactive for a period of time? Inactive here means they have either switch to other tabs, or not touching the browser application.
I guess think I can do this by registering every mouse movement or keyboard movement when users are doing on EVERY page of my application. But the code would be very ugly and hard to maintain. Is there other more elegant ways of doing this?
This is the code I use. It is not mine, but I did modify it to it's 'perfection'.
// Add the following into your HEAD section
var timer = 0;
function set_interval() {
// the interval 'timer' is set as soon as the page loads
timer = setInterval("auto_logout()", 10000);
// the figure '10000' above indicates how many milliseconds the timer be set to.
// Eg: to set it to 5 mins, calculate 5min = 5x60 = 300 sec = 300,000 millisec.
// So set it to 300000
}
function reset_interval() {
//resets the timer. The timer is reset on each of the below events:
// 1. mousemove 2. mouseclick 3. key press 4. scroliing
//first step: clear the existing timer
if (timer != 0) {
clearInterval(timer);
timer = 0;
// second step: implement the timer again
timer = setInterval("auto_logout()", 10000);
// completed the reset of the timer
}
}
function auto_logout() {
// this function will redirect the user to the logout script
window.location = "your_logout_script.php";
}
// Add the following attributes into your BODY tag
onload="set_interval()"
onmousemove="reset_interval()"
onclick="reset_interval()"
onkeypress="reset_interval()"
onscroll="reset_interval()"
Good luck.
If the user is requesting new pages/data from your server on a regular basis, then adjusting the session timeout in PHP should work for this (assuming you are using PHP sessions).
If the concern is that they could be sitting on one page for a good length of time with no trips to the server (e.g. filling out a long form), and you want to distinguish between this and the user simply switching to another window, you could do something like use javascript to request some data using XMLHTTPRequest every five minutes or so to keep the session alive. You could use the window.focus and window.onblur events in javascript to stop and restart this mechanism (I think there are some differences for IE, there is a good explanation here).
A very easy and effective way of doing this is by placing something like this in your HTML HEAD section:
<META HTTP-EQUIV="refresh" CONTENT="1800;URL=logout.php?timeout">
Replace the logout.php?timeout with the appropriate script .. In the example above, if ?timeout is in the query string, I show them a login page with information indicating that they've been logged out due to inactivity.
Replace 1800 with the time in seconds that you wish to allow them to stay inactive before automatically logging them out. Set this to the same time that you have your session expiration set to.
Edit - Another easy mechanism to implement is to have a session variable called last_time, or last_activity, or something along those lines, and set it to a timestamp everytime there is activity. In most of my stuff, I have a general include file that I do this in. In the same file, you could check to ensure that it's within the constraints that you've set forth for an active session. If it's been too long -- just do a 300 redirect to the logout page and display the appropriate inactivity message there.
Good luck!
Ian
We can improve our codes to jquery now
idleTime = 0;
$(document).ready(function() {
var idleInterval = setInterval("timerIncrement()", 60000); // 1 minute //60000
$(this).mousemove(function(e) {
idleTime = 0;
});
$(this).keypress(function(e) {
idleTime = 0;
});
});
function timerIncrement() {
idleTime = idleTime + 1;
if (idleTime >= 5) {
window.location = $('#base_url').val() + 'home/logout_user';
}
}
You can do it more elegantly with underscore and jquery javascript libraries-
$('body').on("click mousemove keyup", _.debounce(function(){
// logout user here
}, 1800000)) // 30 minutes inactivity
It depends how they are "logged in" in the first place. Doesn't the session expiration on the server do this for you? If you really want to do it manually then you could use some javascript in a setTimeout, but thats ugly
Usually the session lifetime is used to determine whether a user is logged in or not. So you could set a flag in the session that represents this state. And if it’s missing (either the user didn’t log in yet or the session timed out), he is considered as not logged in.
You can have a bit of javascript that checks the server every x minutes to see when the user's last activity was. Shouldn't be more than a few lines of code. I would also add a meta refresh if the user has javascript disabled.
I took the timestamp 'now' and check on each click if the delay is less than 3000 seconds or more than billions of seconds, which means that the user just logged in, if it's not it will redirect to logout
var time = 0;
$(document).on('click', function() {
var now = Date.now() / 1000 | 0;
if (now - time < 3000 || now - time > 1480000000) {
time = now;
} else {
window.location.replace("http://url");
}
})
put in header of your java script page.. if you want to avoid the backend calls
Below is the snip-let under script tag :
<script>
var idleTime = 0;
function func(){
console.log(idleTime);
$(this).keypress(function(e) {
idleTime = 0;
});
$(this).click(function(e) {
idleTime = 0;
});
timerIncrement();
}
function timerIncrement() {
console.log("timerIncrement");
console.log(idleTime);
idleTime = idleTime + 1;
if (idleTime >= 1) {
console.log(window.location);
logoutcall(); //API call
window.location = window.location.origin+"/riskoffice_UI/Login";
}
}
setInterval(func,1800000) //Runs the "func" function every second
</script>
Update : localStorage can be use to keep idle time for the application with multiple tabs are opened.
// Check browser support
if (typeof(Storage) !== "undefined") {
// Store an item to localStorage
localStorage.setItem("timeIdle", "0");
console.log(localStorage.getItem("idleTime"));
// Retrieve the added item
} else {
//display this message if browser does not support localStorage
console.log("Sorry, your browser does not support Web Storage.");
}
function func(){
$(this).keypress(function(e) {
localStorage.setItem("timeIdle", "0");
});
$(this).click(function(e) {
localStorage.setItem("timeIdle", "0");
});
timerIncrement();
}
function timerIncrement() {
var timeIdle = localStorage.getItem("timeIdle");
timeIdle = parseInt(timeIdle) + 1;
if (timeIdle >= 1) {
logoutCall();
window.location = window.location.origin+"/riskoffice-ui/Login";
}
localStorage.setItem("timeIdle", timeIdle.toString());
}
setInterval(func,1800000); //Runs the "func" function every second

Categories