Javascript client & asp.net event handler timing issues - how to solve? - javascript

Simple web site with master page and multiple child pages.
In page_load, master page looks for session variable containing a value and if it's there, uses
Page.ClientScript.RegisterStartupScript(this.GetType(), "SessionAlert", "SessionExpireAlert(" + sessionTimeout + ");", true);
This kicks off a timeout alert, which works fine.
There is a server-side button on one child page that effectively ends the user interaction on the page and leaves a message stating "go and log in again if you want to do more stuff". When this button is clicked, I want to clear out the session variable (easy) and end the running timeout warning alert script (not so easy).
As the Master "page_load" event fires BEFORE the button handler, at the time the page reloads, it restarts the timeout script. When it hits the button event handler and clears the session variable, it's too late as the script is already running.
I've tried using "registerclientscriptblock" to inject immediate javascript to call the "clearTimeout()" client side function I have, but it doesn't seem to be able to find the function which exists on the master page and errors.
This seems to be a classic "chicken and egg" scenario and I can't see the wood for the trees. Could someone please point me in the right direction here before I drive myself mad!?
edited to add bit of javascript code:
Currently the master page function "SessionExpireAlert" referenced by the page_load code contains among other things this:
window.updateInterval = setInterval(function () {
seconds--;
document.getElementById("idleTime").innerHTML = convertTime(seconds);
document.getElementById("expireTime").innerHTML = convertTime(seconds);
}, 1000);

RegisterStartupScript will add the script to the end of the body, so the DOM is ready when it runs. As long as you always use RegisterStartupScript after that then the scripts will be added and executed in the order you create them.
Basically, RegisterClientScriptBlock is most likely going to place the script before any scripts added with RegisterStartupScript.

Have you considered putting this in Page_PreRender instead:
Page.ClientScript.RegisterStartupScript(this.GetType(), "SessionAlert", "SessionExpireAlert(" + sessionTimeout + ");", true);
With an appropriate check first to see if it is necessary?

Related

ERROR: 508 (Loop detected)

Well, this isn't like a proper question or anything..
I am just a bit curious, tried searching but couldn't find accurate answer for my problem so I had decided to try out and ask another question out here.
I have this small fun-time project in which you are supposed to keep on clicking a button until you gain the highest clicks among the other players, I have a page ManageClick.php which has the following code in it -
<?
sleep(rand(1,3));
$storage = fopen("TOTAL.txt", "r+");
if (flock($storage, LOCK_EX)) {
$a = fread($storage,filesize("TOTAL.txt"));
$a++;
fseek($storage, 0);
fwrite($storage, $a);
flock($storage, LOCK_UN);
} else {
}
fclose($storage);
?>
The above adds a random delay between 1-3 seconds and then opens a file TOTAL.txt reads it, and adds +1 to the value in the file.
I have a main page Testpage.html which has a simple button and a JQuery function which calls the page ManageClick.php when the button is clicked. However, now the problem arises. Whenever an user rapidly clicks the button in the main page it shows the following error in the Console window-
GET http://domain.tk/ManageClick.php 508 (Loop Detected)
GET http://domain.tk/TOTAL.txt 508 (Loop Detected)
WHERE domain is my website's name.
Any idea what could be causing the following issue? Rapid clicking of the button is one of them which I guess sends multiple requests to the page and causes the 508 error. Also, any possible way in which I could try and fix this error from showing up in the Console?
Also, please note that I am not English... Sorry for it.
PLEASE SEE- Adding the code of my Testpage.html for better quality of help.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(function(){
$("img").click(function() {
var test = $("#Clicks").load("TOTAL.txt");
$.post('ManageClick.php');
});
});
</script>
</head>
<body >
<center>
<img src='ABCD.png'>
<div id='Clicks' style=""></div>
</body>
</html>
If I understood, you have a webpage that has a game in which you call a php script to save how many times the user has clicked on a button.
You say the console (I guess chrome's developper tools or the similar) returns a 508 error as "Loop detected". This is the server telling the client that there might be a loop in the code because it gets called too many times. Well... it's not an automated redirect, it's just you calling it tons of times.
According to your explanation of the game, I would rather save the number of clicks in a javascript variable, and send them only after the game ended. This way, you only call the server one time.
On the other hand, your php code assumes that there's only one user of your website. I mean, you save the value in a file, but it doesn't take in account who's game is it.
Think that if you and I opened the website at the same time, you start adding clicks, and then I add another one, but the count gets saved in the same place.
Edit: Code example
jQuery:
var test = $("#Clicks").load("TOTAL.txt");
$("img").click(function() {
test = parseInt(test) + 1;
});
With this, you load the number previously stored and keep count of the clicks. Next you need to build a function that sends the click count after some idle time (or if you have a timeout per round )
I'll assume that if the user spent 3 seconds without clicking, he's gone, so I update the server. The new jquery would be:
var test = $("#Clicks").load("TOTAL.txt");
var wdt;
$("img").click(function() {
wdt = setTimeout(serversync, 3000);
test = parseInt(test) + 1;
});
function serversync(){
$.post('ManageClick.php?count='+test);
}
In this code I added the serversync function. It runs after 3000 ms have gone for the setTimeout(). This timeout gets fired when the user clicks, but if there's a click again, the timer resets.
Finally, you should pass the new count value to the ManageClick.php script. I passed it as the count GET attribute (which you can retrieve in your php by $_GET['count']
Of course, this is not perfect nor safe (I could easily fake a massive count to be sent to the server, but that's another story), but it's the idea
Your webserver is detecting a long running script based on some configuration. I'd bet if you take out the sleep function, it would no longer detect a loop.
Also, if you are expecting the value in TOTAL.txt to increase, be sure to cast as integer.
$a = fread($storage,filesize("TOTAL.txt"));
$a = (integer) $a; // cast as integer
$a++; // now you can increase it
To further mitigate this issue, if you must keep the lseep() function, use the following steps in your html/js:
click_button (call ajax)
disable_button (while ajax is running/php is sleeping)
accept_ajax_return_value (when ajax responds)
re-enable button (after ajax is complete and can go again)

Javascript - Loop keeps running after page refresh

Today one of the weirdest things i have ever seens just happened.
I have a loop in a page that does a synchronous ajax request for each element of the loop. Since it was taking too long i decided to stop the loop by refreshing the page.
When the page loaded i couldn't click on any element of the page so i checked Firebug console and i saw that the ajax calls of the previous loop were still being done (the loop is set to start after i click on a link, so it can't start as soon as page loads).
To stop the loop i had to close the current tab and open my page in a new one.
It's worth mentioning that i have a datatables table on that page and i have enabled the option to save the table state, maybe this is interfering with my code (the loop itself is not part of the datatables initialization, though it uses data from the table).
I have also noticed that some things of the loop aren't being done. It should've changed the page of the datatable by time to time, and it should've written in the javascript console, both things don't happen after i refresh the page, the ajax calls are still going though.
Here's the code where the loop is contained:
//This variable will contain a reference to the datatable
var oTable;
var isWorking=false;
//Change the datatables page
function changeTablePage(oTable, page, clear){
if(clear){
oTable.fnClearTable();
oTable.fnDraw();
}
oTable.fnPageChange(page);
}
//This part is inside a document.ready block
$(document).on("click", ".validation-all-click", function(event){
if(!isWorking){
isWorking=true;
//saves the current page, will be needed for later
var page=oTable.fnPagingInfo().iPage;
var numberPage=0;
var done=false;
while(!done){
console.log("page: "+numberPage);
changeTablePage(oTable, numberPage, false);
var nNodes = oTable.fnGetNodes();
var len=nNodes.length;
$('.validation-click', nNodes).each(function( index, value ){
//id of the element to be validated
var id=$(value).data("rowid");
//Calls the validation url
$.ajax({
url: "/validate?id="+id,
async: false
});
});
//if the datatables page has 0 items, then it's done
if(len==0){
done=true;
}
numberPage++;
}
//goes back to the original page
changeTablePage(oTable, page, true);
isWorking=false;
}
});
I don't want this behavior to happen, but i have no idea on why it's happening and how to prevent it
Thanks for sharing your story. I don't see any specific question in the post, so I'll just comment on whatever I feel like.
As I understand it, browsers aren't required to redraw the UI while JavaScript is running. Since there's a script blocking on a synchronous ajax request, maybe it's to be expected that you don't see the changes to the table until the loop finishes.
Furthermore, it may also be that the browser isn't required to destroy a page while its scripts are running. That would explain why you saw requests in Firebug after refreshing the page--perhaps the previous copy of the page was still running in a hidden state.
edit: valepu reports in a comment, below, that the table does change while the script is running. That's fine. The browser can probably determine that it can redraw the UI during the ajax call (which doesn't affect the JavaScript environment). valepu also clarifies that the visual updates stop after refreshing the page, though the requests continue to go out. This is also consistent with the idea that the browser has just hidden the previous page (until it finishes) and loaded up a new copy of the page when refreshing.
As for how to prevent it: the most reliable way would be to use asynchronous requests, or otherwise yield between requests. Sorry, folks.
I have solved by adding a variable that will stop the loop when i exit the page:
var stopLoop=false
$( window ).unload(function() {
stopLoop=true;
});
both loops will now check if this variable is false before executing the code inside the loop.
This works on Firefox but not on Chrome though.
-- EDIT --
In the end i have solved by editing the code in order to make the ajax calls asynchronous and using the callback functions to continue the cycle, though it was no simple task (some days later i found a new solution that allowed me to do all that i needed in a single call when i found out how to recover the parameters used by datatables to retrieve data, but this has nothing to do with the original question). So, for future references: expect this "weird" behaviour when making a loop with ajax synchronous calls

Detect first page load with jQuery?

I need to detect the first time a page loads in jQuery so that I can perform some actions only when the page loads the first time a user navigates to that page. Similar to server side code page.ispostbasck. I have tested $(document).ready and it fires every time the page loads so this will not provide what I need. I have also tried the jQuery Load function - it also fires every page load. So by page load an example is that I have an HTML input tag on the page of type button and it does not fire a postback (like an asp.net button) but it does reload the page and fires $(document).ready
Thanks
You will have to use cookie to store first load information:
if (! $.cookie("cookieName")){
// do your stuff
// set cookie now
$.cookie("cookieName", "firstSet", {"expires" : 7})
}
Note: Above example uses jQuery Cookie plugin.
An event doesn't exist that fires only when the page is loaded for the first time.
You should use jQuery's .ready() event, and then persist the fact that you've handled a first time page load using your method of choice (i.e. cookie, session variable, local storage, etc.).
Note: This method will never be fool proof unless you can store this information at the user level in a DB. Otherwise, as soon as the user clears their cookies, or whatever method you choose, the "first time loaded" code will fire again.
I just ran into this problem and this is how I handled it. Keep track of the first time the page loads by using a variable initialLoad:
var initialLoad = true;
$(document).ready(function() {
...
...
...
initialLoad = false;
});
Then in other functions, you can do this:
if (initialLoad) {
//Do work that is done when the page was first refreshed/loaded.
} else {
//Do work when it's not the initial load.
}
This works well for me. If the user is already on the page and some jQuery functions run, I now know if that user just loaded the page or if they were already on the page.
The easy solution is to use jQuery ‘Once’ plugin
$(element).once('class-name', function() {
// your javascript code
});

Click count possible with javascript?

Let's say, in website, I want to display the notice message block whenever people click any of the link at my website more than x number of times. Is that possible to count with javascript and display the notice message block ? And can we count the refresh times also ? Or can it be only done with server side language like php ? Please kindly suggest. Thank you.
With Regards,
To do something when any link is clicked is best done with JQuery's live:
Description: Attach a handler to the
event for all elements which match the
current selector, now and in the
future.
$('a').live('click', function() {
// Live handler called.
});
Even if you add more links in run time, this will take care of it.
For counting refreshes I would do it with ajax calls on window.load event, or if you want to use new tech - store it locally with Html5. :-)
You can do that on the client. However, this will be limited to the browser. The simplest will be to store this information in cookies on the client. For instance with jQuery you could simply intercept clicks like that:
$("a").click(function() {
var clickedUrl = $(this).attr('href');
// Here you update the cookie for the count of clicks for that A URL
});
I would either count page refreshes serverside or probably call an ajax function to update the count when the page loads.
If you want to count clicks you may need to bind an event to each link and then for each indivisual button store the number of clicks in global variables...
You could register each click event on the document by using:
$(document).click(function()
{
// Check the number in the cookie and add another
// click to the cookie
});
Then you could use the jQuery cookie plugin to store that value and check it each time there is a click (in the function above).
here's the cookie plugin: https://github.com/carhartl/jquery-cookie
I threw together a quick example. If you're not worried about doing this from page to page then you don't need cookies, just store it in a variable:
http://www.webdesignandseo.net/jquery/clickcount/

jQuery code repeating problem

I have a piece of code in jQuery that I use to get the contents of an iFrame after you click a link and once the content is completed loading. It works, but I have a problem with it repeating - at least I think that is what it is doing, but I can't figure out why or how.
jQuery JS:
$(".pageSaveButton").bind("click",function(){
var theID = $(this).attr("rel");
$("#fileuploadframe").load(function(){
var response = $("#fileuploadframe").contents().find("html").html();
$.post("siteCreator.script.php",
{action:"savePage",html:response, id: theID},
function(data){
alert(data);
});
});
});
HTML Links ( one of many ):
<a href="templates/1000/files/index.php?pg=0&preview=false"
target="fileuploadframe" class="pageSaveButton" rel="0">Home</a>
So when you click the link, the page that is linked to is opened into the iframe, then the JS fires and waits for the content to finish loading and then grabs the iframe's content and sends it to a PHP script to save to a file. I have a problem where when you click multiple links in a row to save multiple files, the content of all the previous files are overwritten with the current file you have clicked on. I have checked my PHP and am pretty positive the fault is with the JS.
I have noticed that - since I have the PHP's return value alerted - that I get multiple alert boxes. If it is the first link you have clicked on since the main page loaded - then it is fine, but when you click on a second link you get the alert for each of the previous pages you clicked on in addition to the expected alert for the current page.
I hope I have explained well, please let me know if I need to explain better - I really need help resolving this. :) (and if you think the php script is relevant, I can post it - but it only prints out the $_POST variables to let me know what page info is being sent for debugging purposes.)
Thanks ahead of time,
Key
From jQuery .load() documentation I think you need to change your script to:
$(".pageSaveButton").bind("click",function(){
var theID = $(this).attr("rel");
var lnk = $(this).attr("href");//LINK TO LOAD
$("#fileuploadframe").load(lnk,
function(){
//EXECUTE AFTER LOAD IS COMPLETE
var response = $("#fileuploadframe").contents().find("html").html();
$.post("siteCreator.script.php",
{
action:"savePage",
html:response,
id: theID
},
function(data){alert(data);}
);
});
});
As for the multiple responses, you can use something like blockui to disable any further clicks till the .post call returns.
This is because the line
$("#fileuploadframe").load(function(){
Gets executed every time you press a link. Only add the loadhandler to the iframe on document.ready.
If a user has the ability via your UI to click multiple links that trigger this function, then you are going to run into this problem no matter what since you use the single iframe. I would suggest creating an iframe per save process, that why the rendering of one will not affect the other.

Categories

Resources