I have a javascript setInterval that checks an external page every 5 seconds for mail, I am finding sometimes that if I login or click a form submit at the same time as the request goes out, I sometimes find myself looking at a Y or a N (what my JS was to intercept) instead of the real link I wanted to go to.
How does one debug this? I am using firefox with firebug, my app is using PHP with javascript.
EDIT: it's almost as if the onComplete is being missed by java, and it just dumps it as the user is signing in.... it only happens when someone is changing pages and the java is running at the same time.
EDIT 2: If you want to see this for yourself, you'll need visit my site and create an account and go through the signup process (2-3 mins to do tops), the website is http://mikesandmegs.com and the beta password is goldfish. What you want to do is login just as the check mail sends its request off. Its like I need to cancel something or tell java to throw the callback out or something. You should see the requests every 5 seconds, (well it adds 5 seconds each request) but you'll see. It may take a couple try's or some luck, but it is reproducible.
This is the javascript that is running (i think I have it all posted) If I seem to be missing anything, let me know. I also posted an htnl input html that the javascript checks...
<input id="hasMail" type="hidden" value="y">
<script type='text/javascript'>
mailTimer = setInterval("checkMail();", 10000);
function checkMail()
{
// should we check the mail now?
if ($('hasMail').value == "y")
{
// remove mail new mail alert (mail-check.php returns y or n
new Ajax.Request('mail-check.php',
{
method: 'post',
postBody: '',
onComplete: checkMailNotify
});
}
}
function checkMailNotify(req)
{
if (req.responseText.length > 5)
{
$('hasMail').value = "n";
clearInterval (mailTimer);
return;
}
if (req.responseText == "y")
{
$('hasMail').value = "n";
$('topMessage').update('You have new mail...');
$('alertBox').appear();
clearInterval (mailTimer);
}
else
{
clearInterval (mailTimer);
mailInterval = mailInterval + 5000;
mailTimer = setInterval("checkMail();", mailInterval);
}
}
</script>
I know this is nowhere near a solution, but it WILL help to increase the 5 second interval, even to something like 30 seconds. I've done work with mailservers before, and we often came across problems where people would have e.g their iphone as well as their desktop mail client ping the server at very short intervals. This would result in confusing (to them) failures because of locks.
So yeah, 5 seconds for messages is very quick (it doesn't look like chat but rather just messages, is that right?). At best if you do that then the problem will happen a lot less if it all. You will however have the horrible knowledge that it can happen.
Please don't take this as an attempt at a solution to your problem. just a suggestion.
I think what's happening is that while changing pages, the data from the mail-check.php is clashing with the new request that is coming back from the network at the same time. I think a possible solution is to disable the setInterval whenever you change a page or submit a form, then re-enable it after loading the new data.
Something like:
<input type="button" onClick="clearInterval('mailTimer'); this.submit()" />
...
Related
I have been looking for several answers around the web and here, but I could not find one that solved my problem.
I am making several JQuery ajax calls to the same PHP script. In a first place, I was seeing each call beeing executed only after the previous was done. I changed this by adding session_write_close() to the beginning of the script, to prevent PHP from locking the session to the other ajax calls. I am not editing the $_SESSION variable in the script, only reading from it.
Now the behaviour is better, but instead of having all my requests starting simultaneously, they go by block, as you can see on the image:
What should I do to get all my requests starting at the same moment and actually beeing executed without any link with the other requests ?
For better clarity, here is my js code:
var promises = [];
listMenu.forEach(function(menu) {
var res = sendMenu(menu);//AJAX CALL
promises.push(res);
});
$.when.apply(null, promises).done(function() {
$('#ajaxSpinner').hide();
listMenu = null;
});
My PHP script is just inserting/updating data, and start with:
<?php
session_start();
session_write_close();
//execution
I guess I am doing things the wrong way. Thank you in advance for you precious help !!
Thomas
This is probably a browser limitation, there is a maximum number of concurrent connections to a single server per browser instance. In Chrome this has been 6, which reflects the size of the blocks shown in your screenshot. Though this is from 09, I believe it's still relevant: https://bugs.chromium.org/p/chromium/issues/detail?id=12066
I have this form:
<form method="post" action="secret.php">
<label for="pw">Password: </label><input type="password" name="pw" id="pw" />
</form>
This is secret.php:
<?php
if(isset($_POST["pw"])) {
if($_POST["pw"] == "hello") {
echo("<strong>Good pw.</strong><br />");
} else {
echo("<strong>Bad pw.</strong><br />");
echo("Back");
sleep(5);
}
} else {
header("Location: /tut/first/form.php");
}
?>
What happens is that if the password is wrong, it sleeps before displaying Bad pw. When I submit the form, it sleeps 5 seconds on the form page, and then changes page and displays Bad pw. Why?
What is happening is that you are causing the PHP script to sleep. The script must complete before it sends the result back to the client (the browser).* So you are causing the script to take 5 seconds longer before it responds to the client that it wasn't a good password.
Since you are not trying to avoid a brute force situation here I would suggest something like this:
<?php
if(isset($_POST["pw"])) {
if($_POST["pw"] == "hello") {
echo("<strong>Good pw.</strong><br />");
} else {
echo("<strong>Bad pw.</strong><br />");
echo("<script type=\"text/javascript\">");
echo ("setTimeout(function() {");
echo ("window.location = form.php;"); //might need a more complete URL here
echo ("}, 5)"); //sleep for 5 seconds before redirecting
echo("</script>");
sleep(5);
}
} else {
header("Location: /tut/first/form.php");
}
?>
*The output is actually sent back as it's written in the PHP script but with buffering you don't see this making much of a difference except in headers and very large pages.
You need to look into output buffering, although from what I see, the logic is flawed.
This may help
If you want to echo something to the browser right away, try doing flush() when you want to flush the output buffer to the browser. Also, you may need to disable compression (like gzip) which can interfere with output buffering.
However with that said, you're going about this completely wrong. All that the user would have to do is open up another tab / refresh and the server will validate the login information again, so doing sleep() isn't going to have the effect you think it is.
I have actually designed something similar to this and this is what I did:
Create a database table called failed_logins and another called login_bans and both are based on IP address. Every time a user provides incorrect information, add an entry in the failed_logins table. What you want to do is tier it so that after the first login, the user is banned for 5 seconds, after the second, it goes up to 15 seconds and 3 or more within a certain period (like say 2 hours) the user is banned for 45 seconds. This is all done server-side so that there is nothing the user can do to circumvent the ban. So you will have to check their IP every time they access the page to see if their IP has been banned.
Then on the client-side display a countdown timer containing the number of seconds remaining in the ban and disable the submit button.
I have a chat box using jQuery and php.
setInterval(
function(){
if($('#session_container').children().length > 0){
if(localStorage['group_id']){
var group_id = localStorage['group_id'];
var session_id = localStorage['session_id'];
var gsid = 'GSID' + group_id + session_id;
$('#chatbox').load('php/chatbox.php', {'group_id' : group_id, 'session_id' : session_id},
function(){
$('#chatbox').find('tr:even').addClass('alt');
if($('#chatbox').children().length == 0){
localStorage.clear();
window.location.replace('chatro_main.php');
}
}
);
}else{
}
}
}, 1000);
As you can see from the code above, the script runs every one second which I think is very aggressive and I think it's also wasting power(my laptop's battery seems to be draining faster when I was running this). Is there a better way of doing this. Something like not reloading the content while the user is on another tab on the browser window. Or something like updating only the content if another user sent a message?
If you know of another technology that could do this in a more optimal way, you could also mention it.
There are several possible answers to this question:
Don't use setInterval, but repeatedly setTimeout and adjust your timeout. The idea is, that you first try like every 10 seconds, and then increase the time, if there is no action. So the intervals would be: 10, 20, 40, message received, 10, 20, message received, 10, ... You have to adjust the factor you will actually increase the timeout to fit your needs.
Implement it using WebSockets (see comment of #Christian Varga)
Use node.js as server side language, which interacts with client side javascript pretty well. You can have node.js broadcast messages to all clients, so you actually have a two-way connection there (I think they use WebSockets and as fallback something like comet.js, but I am not sure, I just saw it done once)
Actually this is not an answer but i can't make a comment cause of my rep. I had a chat like this, but i had a var named chatState, when chatState is 1(or true) fires interval for every second when no msg received for a while chatSate goes for 0(false) and clears that interval and starts a new one checks for every 10 seconds if there is someone type anything to chat? Not sure this is a good way but i tought that would be better for server cause less request, but as i said not sure is this a good way so this is would be a comment instead of answer.
Well, i was trying to reach a solution and i thought this might work:
On the PHP file:
$liguem = getdate();
$liguemoff = $_COOKIE['liguemoff'];
$liguemon = $_COOKIE['liguemon'];
if(empty($liguemoff)){
setcookie('liguemoff',$liguem[0],time() + (50000));
}
setcookie('liguemon',$liguem[0],time() + (20000));
$body->assign("COOKIE2", $liguemoff);
$body->assign("COOKIE3", $liguemon);
This has some body assign because I'm working with XTemplate, but the PHP is just PHP.
Now on the index file, some JavaScript:
var cookie2 = {COOKIE2};
var cookie3 = {COOKIE3};
if( cookie3-cookie2 > 60){
alert('alerta');
};
Truth is that it works! People might not be navigating, but it is what i want, the pop up will only open after the visitor sees at least 2 pages (Server-side thing).
The main problem is, that i CAN'T make the function popup(); to trigger where i have the ALERT displaying. The ALERT is working alright though.... Any hints?
PS:
This is the popthat(); function:
function popthat(){
$("#darkside").css('opacity','0.3').fadeIn('slow');
$("#darkside").click(function () {
$(this).css('opacity','1').fadeIn('fast');
$("#liguem").hide();
});
$("#liguem").corner();
$("#liguem").hide();
$("#liguem").delay(200).css('visibility','visible');
$("#liguem").fadeIn('fast');
}
You can set a timeout to display your popup after a specified amount of time. This amount of time can be dicated by your PHP since the server-side code will be able to track the amount of time on the site through page-views. This way the popup can display after 60 seconds on the site even if the user is not navigating to another page.
Something like:
setTimeout(popthat, <?php echo $_COOKIE[...]; ?>);
Your PHP would echo the number of milliseconds until the popup should display.
A note: when you replace your alert() with the popthat() function the DOM may not be ready and popthat() won't be able to work because it won't find any elements that match your selectors. Try running your code on document.ready ($(function() {});).
Browsers automatically block popups initialized on page load, because nobody likes these sorts of popups.
When you do an alert(), execution of your script stops. alert() is a blocking function, and nothing will happen until it has moved on.
I don't know if you just made a typo, but your function is called popthat(), and in your statement you said you called the function popup(). You need to change popup(); to popthat(); for this to work, unless as I said that was a mistake.
I have a PHP script (let's call it execute.php) that draws the whole page (HTML tags and body tags etc.) at the beginning and, afer that, executes some commands (C++ programs) in the background. It then waits for these programs to terminate (some depend on the results of others, so they may be executed sequentially) and then has a JavaScript that auto-submits a form to another PHP script (which we will call results.php) because results.php needs the POST-information from the previous script.
execute.php:
<?php
print"
<html>
<body>
Some HTML code here
</body>
</html>
";
// Here come some C++-program calls
$pid_program1 = run_in_background($program1)
$pid_program2 = run_in_background($program2)
while (is_running($pid_program1) or is_running($pid_program2) )
{
//echo(".");
sleep(1);
}
// Here come some later C++-program calls that execute quickly
$pid_program3 = run_in_background($program3)
$pid_program4 = run_in_background($program4)
while (is_running($pid_program3) or is_running($pid_program4) )
{
sleep(1);
}
...
// We are now finished
print "
<form action=\"results.php\" id=\"go_to_results\" method=\"POST\">
<input type='hidden' name=\"session_id\" value=\"XYZ\">
</form>
<script type=\"text/javascript\">
AutoSubmitForm( 'go_to_results' );
</script>
";
This works nicely if the C++ programs 1 and 2 execute quickly. However, when they take their time (around 25 minutes in total), the PHP script seems to fail to continue. Interestingly the C++ programs 3 and 4 are nevertheless executed and produce the expected outputs etc.
However, when I put a echo("."); in the first while-loop before the sleep(), it works and continues until the JavaScript autosubmit.
So it seems to me that the remaining PHP code (including the autosubmit) is, for whatever reason, not send when there is no output in the first while loop.
I have also tried using set_time_limit(0) and ignore_user_abort(true) and different other things like writing to an outputbuffer (don't want to clutter the already finally displayed webpage) instead of the echo, but none of these work.
When I run the same scripts on a machine with multiple cores, so that program1 and 2 can be executed in parallel, it also works, without the echo(".").
So I am currently very confused and can't find any error messages in the apache log or PHP log and thus would really appreciate your thoughts on this one.
EDIT
Thanks again for your suggestions so far.
I have now adopted a solution involving (really simple) AJAX and it's definitely nicer this way.
However, if the C++-programs executions take "longer" it is not autosubmitting to the results-page, which is actually created this time (failed to do so before).
Basically what I have done is:
process.php:
<?php
$params = "someparam=1";
?>
<html>
<body>
<script type="text/javascript">
function run_analyses(params){
// Use AJAX to execute the programs independenantly in the background
// Allows for the user to close the process-page and come back at a later point to the results-link, w/o need to wait.
if (window.XMLHttpRequest)
{
http_request = new XMLHttpRequest();
}
else
{
//Fallback for IE5 and IE6, as these don't support the above writing/code
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}
//Is http_request still false
if (!http_request)
{
alert('Ende :( Kann keine XMLHTTP-Instanz erzeugen');
}
http_request.onreadystatechange=function(){
if (http_request.readyState==4 && http_request.status==200){
// Maybe used to display the progress of the execution
//document.getElementById("output").innerHTML=http_request.responseText;
// Call of programs is finished -> Go to the results-page
document.getElementById( "go_to_results" ).submit();
}
};
http_request.open("POST","execute.php",true);
//Send the proper header information along with the request
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.setRequestHeader("Content-length", params.length);
http_request.setRequestHeader("Connection", "close");
http_request.send(params);
};
</script>
<?php
// Do some HTML-markup
...
// Start the programs!
print "
<script type=\"text/javascript\">
run_analyses('".$params."');
</script>
<form action=\"results.html" id=\"go_to_results\" method=\"POST\">
<input type='hidden' name=\"session_id\" value=\"XYZ\">
</form>
?>
</html>
</body>
and execute.php contains the C++-program calls, waiting-routines and finally, via "include("results.php")" the creation of the results-page.
Again, for "not so long" program executions, the autosubmission works as expected, but not if it takes "longer". By "longer" I mean around 25 minutes.
I have absolutely no idea what could cause this as again, there are no error-messages to be found.
Am I missing a crucial configuration option there (apache, php, etc.)?
EDIT
As it turned out, letting the requested PHP-script "echo" something repeatedly prevents the timeout. So it is basically the same as for the PHP-solution without AJAX, but this time, since the responseText of the AJAX-request is not necessarily needed, the progress-page is not cluttered and it may be used as a workaround. Specifically, I would not necessarily recommend it a as a general solution or good-practice.
It occurs to me that a better approach would be to:
Output the complete HTML page
Show a loading message to the user
Send an AJAX request to start the external program
Wait for callback (waiting for external program to finish)
Repeat steps 3 and 4 until all program have been executed
Update the page to tell the user what is going on
Submit the form
This way, you get the HTML to the user as quickly as possible, then you execute the programs sequentially in an orderly and controlled fashion without worrying about hitting the max_execution_time threshold. This also enables you to keep your user informed - after each AJAX callback, you can tell the user that "program ABC has completed, starting DEF..." and so on.
EDIT
Per request, I'll add an outline of how this could be implemented. A caveat, too: If you are going to be adding more javascript-derived functionality to your page, you'll want to consider using a library like jQuery or mootools (my personal favorite). This is a decision you should make right away - if you aren't going to be doing a lot of javascript except this, then a library will only bloat your project, but if you are going to be adding a lot of javascript, you don't want to have to come back later and re-write your code because you add a library 3/4 of the way through the project.
I've used mootools to create this demonstration, but it isn't necessary or even advisable to add mootools if this is the only thing you're going to use it for. It is simply easier for me to write an example really quick without having to stop and think :)
First, the main page. We'll call this page view.php. This should contain your initial HTML as well as the javascript that will fire off the AJAX requests. Basically, this entire jsFiddle would be view.php: http://jsfiddle.net/WPnEy/1/
Now, execute.php looks like this:
$program_name = isset($_POST['program_name']) ? $_POST['program_name'] : false;
switch ($program_name) {
case 'program1':
$program_path = '/path/to/executable/';
$friendly_name = 'Some program 1';
break;
case 'program2':
$program_path = '/path/to/executable/';
$friendly_name = 'Some program 2';
break;
case 'program3':
$program_path = '/path/to/executable/';
$friendly_name = 'Some program 3';
break;
case 'program4':
$program_path = '/path/to/executable/';
$friendly_name = 'Some program 4';
break;
default:
die(json_encode(array(
'program_name'=>'Invalid',
'status'=>'FAILED',
'error'->true,
'error_msg'=>'Invalid program'
)));
break;
}
$pid = run_in_background($program_path)
while (is_running(pid)) {
sleep(1);
}
// check here for errors, get any error messages you might have
$error = false;
$error_msg = '';
// use this for failures that are not necessarily errors...
$status = 'OK';
die(json_encode(array(
'program_name'=>$friendly_name,
'status'=>$status,
'error'->$error,
'error_msg'=>$error_msg
)));
execute.php would then be called once for each program. The $friendly_program variable gives you a way to send back something for the user to see. The switch statement there makes sure that the script isn't being asked to execute anything you aren't expecting. The program is executed, and when it is done you send along a little package of information with the status, the friendly name, any errors, etc. This comes into the javascript on view.php, which then decides if there are more programs to run. If so, it will call execute.php again... if not, it will submit the form.
This seems rather convoluted... And very risky. Any network glitches, the user's browser closing for whatever reason, and even a firewall timing out, and this script is aborted.
Why not run the whole thing in the background?
<?php
session_start();
$_SESSION['background_run_is_done'] = false;
session_write_close(); // release session file lock
set_time_limit(0);
ignore_user_abort(true); // allow job to keep running even if client disconnects.
.... your external stuff here ...
if ($successfully_completed) {
session_start(); // re-open session file to update value
$_SESSION['background_run_is_done'] = TRUE;
}
... use curl to submit job completion post here ...
?>
This disconnects the state of the user's browser from the processing of the jobs. You then just have your client-side code ping the server occasionally to monitor the job's progress.
Launching and managing multiple and long-running processes from a webserver PHP process is fraught with complications and complexity. It's also very different on different platforms (you didn't say which you are using).
Handling the invocation of these processes synchronously from the execution of your PHP is not the way to address this. You really need to run the programs in a seperate session group - and use (e.g.) Ajax or Comet to poll the status of them.