I created a function in php which send request to a server at every X seconds. Let's say a watcher. I start that watcher via ajax request from javascript using button. Also a button which stops that watcher.
$continue = true;
if(isset($_POST["start"])) {
global $continue;
$continue = true;
checkCredentials();
while($continue) {
watch();
sleep(60);
}
}
if(isset($_POST["stop"])) {
global $continue;
checkCredentials();
$continue = false;
}
$.ajax({
url: "watch.php",
data: { ztop: true },
type: "post",
success: function (result) {
$result.append("<p>" + result.message + "</p>");
}
});
I want to use a thread to do this in php but I don't know how to do ... I want to stop watch when press on button. But the second isset will be executed after 60 seconds... How to stop the watch executed in first isset ?
Related
I have a weak server
When clients repeatedly request ajax service, the server stops working
Frequent demand ajax
My server is weakening
I want to make only one request. Upon completion he will be able to make another request
function checkItemd(item_id){
$("#checkBtn"+item_id).html("Processing..(Wait)").removeClass("btn-success").addClass("btn-primary");
alert("One tool checked at a time - Click OK");
var payload_string = $("#payload_form").serialize();
$.ajax({
type:"POST",
url:"ajax-item-check",
data:payload_string + "&itemId=" + item_id,
dataType:"json",
success:function(result){
if (result.result=="success"){
if (result.works=="success"){
var checkBtnMessage = result.response ? result.response : "'Sent to ' Email ";
$("#checkBtn"+item_id).html(checkBtnMessage).removeClass("btn-primary").addClass("btn-success");
}else{
$("#checkBtn"+item_id).html("Error").removeClass("btn-primary").addClass("btn-danger");
setTimeout('removeRow('+item_id+');',1000);
}
}else{
$("#checkBtn"+item_id).html("Not available to sellers").removeClass("btn-primary").addClass("btn-warning");
}
}
});
return false;
If you want to stop the user making multiple parallel requests, you can just set a flag which causes the function code not to be executable if the request is already in progress.
e.g. look at the requestInProgress flag in this example:
var requestInProgress = false;
function checkItemd(item_id) {
if (requestInProgress == true) return false;
$("#checkBtn"+item_id).html("Processing..(Wait)").removeClass("btn-success").addClass("btn-primary");
alert("One tool checked at a time - Click OK");
var payload_string = $("#payload_form").serialize();
requestInProgress = true;
$.ajax({
type:"POST",
url:"ajax-item-check",
data:payload_string + "&itemId=" + item_id,
dataType:"json",
success:function(result){
requestInProgress = false;
if (result.result=="success") {
if (result.works=="success") {
var checkBtnMessage = result.response ? result.response : "'Sent to ' Email ";
$("#checkBtn"+item_id).html(checkBtnMessage).removeClass("btn-primary").addClass("btn-success");
}else{
$("#checkBtn"+item_id).html("Error").removeClass("btn-primary").addClass("btn-danger");
setTimeout('removeRow('+item_id+');',1000);
}
}else{
$("#checkBtn"+item_id).html("Not available to sellers").removeClass("btn-primary").addClass("btn-warning");
}
}
});
}
N.B. you might want to add an "error" callback so you can set the flag false again in the event of any kind of unexpected problem with the request. Otherwise the user would have to refresh the page before they could make the request again.
Click on a button executes this Ajax request
$.ajax({
type: "GET",
url: "json-responses.php?fct=validationCode&userMail=" + userMail,
success: sendValidationCode()
});
if successfull the sendValidationCode() function is invoked which executes another Ajax request
function sendValidationCode()
{
$.ajax({
type: "GET",
url: "json-responses.php?fct=sendValidationCode&userMail=" + userMail,
success: function()
{
location.replace("reset-forgotten-pw?user=" + userMail);
}
});
}
Here is the code from the json-responses.php file :
if ($_GET['fct'] == 'validationCode')
{
$_SESSION['v_Code'] = random_str(6, '0123456789');
$result = createValidationCode($connectionObject, $_GET['userMail'], do_crypt($_SESSION['v_Code']));
echo $result;
}
if ($_GET['fct'] == 'sendValidationCode')
{
$volTo = $_GET['userMail'];
$volAckString = $image . "<h1>Password assistance</h1><p>To verify your identity, please use the following code:</p>".$_SESSION['v_Code'].;
unset($_SESSION['v_Code']);
}
I was assuming that as the 'validationCode' part is called before the $_SESSION['V_Code'] variable would be set and available when the second file invokes 'sendValidationCode' file. However the mail the user receives does not contain any validation code. Now if I restart the process (means the session remains open during the 'validationCode' part I get a new $_SESSION variable and in the 'sendValidationCode' part the "old" $_SESSION['v_Code'] is sent to the user. (Besides the unset.... does not have any effect.)
In a commercial project I need to periodically monitor SMTP and Accounting servers to see if its running and working properly.
if its dead update a table in mysql.
I cant install any 3rd party app on server hosting php script or use exec or modify php settings through php_ini_set
each task takes about 10 to 30 seconds
I tried to run tasks through Jquery ajax calls
and it worked , but the problem is when the jquery request is running you cant navigate to any other page and xhr.abort(); is not working , and stucks on loading until jquery task finishes.
This is what i tried in my js file
var monitor_running = false;
var xhr;
function monitor() {
if (document.readyState === "complete") {
if (monitor_running === false) {
monitor_call();
}
else {
console.log("jobs Already running ===>");
}
}
}
window.onbeforeunload = function () {
console.log(xhr);
xhr.abort();
alert(xhr.status);
};
setInterval(monitor, monitor_interval * 1000);
function monitor_call() {
monitor_running = true;
console.log("jobs running");
xhr = $.ajax({url: './ajax.php',
data: {
cmd: 'monitor'
},
type: 'post',
async: true,
success: function (output) {
monitor_running = false;
console.log(output + " job is finished");
}
});
}
and in php page :
<?php
include_once '../includes/config.php';
$tpl_obj = new template('admin');
$navigation_obj = new navigation();
$auth = $navigation_obj->admin_is_auth();
if (!$auth) {
die('Auth Failed !');
}
function monitor() {
sleep(10);
echo 'done';
// $monReport['acc'] = monitor::domon('acc');
// $monReport['smtp'] = monitor::domon('smtp');
// $monReport['payment'] = monitor::domon('payment');
// $monReport['dns'] = monitor::domon('dns');
// return json_encode($monReport);
}
$cmd_post = filter_input(INPUT_POST, 'cmd');
$cmd_get = filter_input(INPUT_GET, 'cmd');
if ($cmd_post == 'monitor') {
echo monitor();
}
I'm currently trying to get a PHP loop status and update a HTML5 progress bar.
The loop is triggered by a button click and set to 5000 with 1sec sleep() after every execution. I of course also made an Ajax request to which reuqests the current loop number every second and update the progress bar. However the request always waits until the loop is completed and shows me a number like "1234567891011..."
This is my JQuery code which is very simple because it's only for testing and learning purpose
function getStatus() {
$.ajax({
url : 'ajax.php',
dataType: "html",
type: "POST",
data: {request: 'request',},
success: function( data ) {
//Call function to update status on the loading bar
updateBar(data);
}
});
//Update loading bar
function updateBar(data) {
$('progress').attr('value', data);
}
}
function setGo() {
$.ajax({
url : 'ajax.php',
dataType: "html",
type: "POST",
//async: false,
data: {status: 'GO',},
success: function( data ) {}
});
}
$('#start').click(function(event) {
setGo();
setInterval(function() {
getStatus();
}, 1000);
});
This is my php Code
<?php
//Overwrite php execution limit
set_time_limit(120);
if($_POST['status'] = 'GO') {
$number = 5000;
$counter = 0;
for($i=0; $i != $number; $i++) {
$counter++;
sleep(1);
if(isset($_POST['request'])) {
echo $counter;
}
}
}
?>
I tried a lot of different ways and read a lot of posts but somehow nothing worked for me.
Hope someone got an idea.
Take a good look at your "echo $counter;" part in your PHP script, that's in a (5000 times) loop.
After the PHP code is interpreted and executed, the web server sends resulting output to its client, usually in form of a part of the generated web page – for example, PHP code can generate a web page's HTML code
From PHP's wiki page
This basically means that the whole php file will always be executed before returning the output. The loop will be executed 5000 times before returning the output.
Basically I'm looking for a solution where a user is notified five minutes before the session expires.
The ideal solution will be count down notification that will have an option to renew the session.
If the countdown timer expires without the user refreshing the page, I need to log them out.
Since the session will be refreshed as soon as you go back server-side and the script calls session_start() you really need to do this in Javascript. However if the user has two browser windows open with a split session and one is inactive, while the user is still generating traffic with the other, then the javascript in the idle window would incorrectly report that the session was about to expire. So you'd need to implement your own ajax wrapper to detect the age of the session without calling session_start().
Something like:
$session_id=$_REQUEST[session_name()];
// if you use the default handler:
$session_last_access=filemtime(session_save_path() . '/' . $session_id);
$time_left=time() + session_cache_expire() - $session_last_access;
C.
Depends on what exactly you want to achieve. When someone uses multiple tabs/windows, a window can stay open for very long without the session expiring. AJAX operations complicate things even further. If you want accurate notifications, you will have to set up a timer, and when it fires, check via an AJAX request (taking care not to renew the session) whether the estimate is still accurate.
Added this script in view:
`
if(isSessionAlive >0)
{
var timer = {
time: 0,
now: function(){ return (new Date()).getTime(); },
start: function(){ this.time = this.now(); },
since: function(){ return this.now()-this.time; }
}
var timerId;
sess_expiration = <?=($this->config->config["sess_expiration"]*1000)?>;
alertTime = <?=($this->config->config["sess_time_to_alert"])?>;
timerId = window.setTimeout("pingCI()",sess_expiration-((alertTime*1000)));
jsBaseurl = "<?=($this->config->config["base_url"])?>";
}
function resetTimer(resetTime)
{
//alert('RESET Time'+resetTime);
window.clearTimeout(timerId);
timerId = window.setTimeout("pingCI()", resetTime);
return;
}
function pingCI()
{
if(isSessionAlive > 0)
{
$.ajax({
type: "POST",
url: "<?= site_url('users/getSessionTimeLeft') ?>/",
data: "sessid=<?=$this->session->userdata("session_id")?>",
success: function(transport)
{
response = transport;
if(response=='')
{
parent.location.assign(jsBaseurl+'users/logout');
}
else if((response<=(alertTime*1000)) || (response-1000<=(alertTime*1000)))
{
alertSessionTimeOut(response);
}
else
{
resetTime = eval((response - alertTime)*1000);
resetTimer(resetTime);
}
}
});
}
}
function alertSessionTimeOut(alertTimeExp)
{
if(isSessionAlive>0)
{
var response='';
var timerIdEnd;
timerAlert = window.setTimeout("forceLogout()",alertTimeExp*1000);
timer.start(); // start counting my friend...
fConfirm = confirm('Your Session is about to time out. Please click OK to continue the session');
if(timer.since() >= (alertTime*1000))
{
parent.location.assign(jsBaseurl+'users/logout');
}
if(fConfirm ==true)
{
$.ajax({
type: "POST",
url: "<?= site_url('users/keepAlive') ?>/",
data: "sessid=<?=$this->session->userdata("session_id")?>",
success: function(transport)
{
response = transport;
if(response=='')
{
parent.location.assign(jsBaseurl+'users/logout');
}
window.clearTimeout(timerAlert);
resetTimer(sess_expiration-((alertTime)*1000));
}
});
}
else
{
//parent.location.assign(jsBaseurl+'users/logout');
window.clearTimeout(timerAlert);
window.clearTimeout(timerId);
}
}
}
function forceLogout()
{
parent.location.assign(jsBaseurl+'users/logout');
}
And in Users Controller:
function getSessionTimeLeft()
{
$ci = & get_instance();
$SessTimeLeft = 0;
$SessExpTime = $ci->config->config["sess_expiration"];
$CurrTime = time();
$lastActivity = $this->session->userdata['last_activity'];
$SessTimeLeft = ($SessExpTime - ($CurrTime - $lastActivity))*1000;
print $SessTimeLeft;
}
function keepAlive()
{
$this->load->library('session');
$this->session->set_userdata(array('last_activity'=>time()));
if(isset($this->session->userdata["user_id"])) print 'ALIVE';
else print '';
}
`
One way is to store in one javascript variable the time remaining, and update the variable in every page refresh
Create one javascript function with one settimeout that verifies the value of the variable that you set in 1.)
Regards,
Pedro