Countdown timer-php+mysql+js - javascript

I am working on online examination. In which the examination duration will fetch by mysql(in minutes). I want to show the countdown time on the top of the page.
currently I am using
http://javascript.internet.com/time-date/countdown-timer.html
but the main problem is .. when every time a new question display ..the page get refresh and ..timer reset again from start.
Please help me where is the main problem?
or any other example if you want to suggest?
Thanks

Before running the test you need to calculate exact test end time on the server side and save it into session:
<?php
if (empty($_SESSION['test_will_end_by'])) {
$_SESSION['test_will_end_by'] = time() + $test_duration_in_seconds;
}
?>
Then, if you provide it to your client-side script from HTML:
Time left:
<span class="timer" data-end="<?php
echo date(DateTime::RFC1123, $_SESSION['test_will_end_by']);
?>"></span>
Add this code into your jQuery DOM-ready handler to start all timers on a page:
$('.timer').each(function() {
var target = new Date($(this).data('end')), update, $this = $(this);
(update = function () {
var now = new Date();
$this.text((new Date(target - now)).toUTCString().split(' ')[4]);
if (Math.floor((target - now)/1000) == 0) return; // timer stops
setTimeout(update, 1000);
})();
});

Every time you refresh the page, the JavaScript code will run again, so the timer will be reset. To solve this problem, get the content without refreshing the page, that is : Ajax.

You can store the current value in a cookie using the form submit or page beforeunload events. Then when a new page loads, get the remaining time and keep counting down. This also allows for some network latency.
Note that the user may be able to access and modify the value of the cookie.

Store the question start time in session, when ever page refreshes get the session start time difference from server and display them in web page. The increment part you can do from the client side javascript code without using AJAX.

Related

countdown function keeps on looping after 12 seconds - please assist

I have a PHP page that consists of many data and functions of it, so whenever I click to go to this specific page it loads around 12 seconds. So to notify the user, I have included the below code but it refreshes again and again by decreasing <=0 but the data is already there after 12 seconds completed. Please assist on which line of code I need to change below. Thank you.
<p align="center">You will be redirected in <span id='counter'>12</span> second(s).</p>
<script type='text/javascript'>
function countdown() {
var i = document.getElementById('counter');
if (parseInt(i.innerHTML)<=0) {
location.href = 'studentPredict.php';
}
i.innerHTML = parseInt(i.innerHTML)-1;
}
setInterval(function(){ countdown(); },1000);
</script>'";
Like I said in the comments.
I think you can better load the content with an ajax call instead of a redirect. And show the user a message that the content is loading if you whant you can add a timmer to it so the visitor know how long it will probelly take.
More info about ajax: https://www.w3schools.com/js/js_ajax_intro.asp
If the data doent change that much, cache the data for a specific time so the next request will load much faster. You can cache it in a file or in your system ram with apcu, redis, memcache... Some server dont allow ram cache you need an external server(wich i don't recommend) or cache it in files

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)

reload php page with javascript

I have drawn a chess board in a php page. Every piece is set as draggable, and every tile as droppable. Once a piece is dropped on a tile, I'd like to reload the php page so the board can be drawn anew along with new positions.
How can I do that: reloading the php page with javascript, without displaying a window asking for confirmation such as "To display this page, Firefox must send information that will repeat any action (such as a search or order confirmation) that was performed earlier. ->Cancel; Resend" ?
Or perhaps there are better solutions?
If you want to avoid having refresh reporting data (for any reason, including the user clicking the reload button) then use the POST-REDIRECT-GET pattern (http://en.wikipedia.org/wiki/Post/Redirect/Get). Read that, it will explain what to do.
Quick solution: you could try:
window.location.reload(true); //true sets request type to GET
Use GET, instead of POST and the dialog box you are getting will go away.
Good luck!
Make use of
window.location.reload();
will refresh automatically
<script>
var timer = null;
function auto_reload()
{
window.location = 'http://domain.com/page.php'; //your page location
}
</script>
<!-- Reload page every 10 seconds. -->
<body onload="timer = setTimeout('auto_reload()',10000);">
reference http://davidwalsh.name/automatically-refresh-page-javascript-meta-tags

jquery refresh div when content changes

I have index.php and images.php. And what I want is that a certain div on index.php is getting it's content from images.php automatically and refresh when new content is present on images.php. I currently have this:
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function() {
$('#images').load('images.php');
}, 500);
});
This works fine, but it refreshes the div every .5s which I don't want, I want it to detect when new content has been inserted into images.php then load it in.
But the thing is, on images.php I have some timestamps (1 minute ago, etc.). And jQuery will detect those as changes and will then refresh.
Is there a way to count the number of image tags (<img>) on the images.php page and compare them with the number of image tags in the div on the index.php page, and then if they are not equal, refresh the div on index.php.
The short answer is - no.
You should understand, that there's server side of your code and client side. Whenever browser sends a request, it gets a formatted html page (not a php script to execute) and gets all embedded resources (images, css, js files etc).
After that no communication is done between the client (browser) and a server (your web server). For you to get updated 'images.php' page you'd need to send a notification from a server to all browsers looking at your page currently (which you don't know - you'd need a fixed connection with them, but html protocol is stateless meaning there's no easy way of accomplishing it).
So, the easiest way is to have browser ping server in a timely fashion - every n seconds. Though, it would probably be better to fetch not all images every n seconds, but the last change date - and have some logic to fetch new data when it has a newer change date - this would reduce amount of traffic sent by your application.
var imageWrapper = $('#images'),
imageCount = $imageWrapper.find('img').length;
setInterval(function() {
$.get('images.php', function (html) {
html = $(html);
if ( html.find('img').length > imageCount ) {
$imageWrapper.html( html );
}
});
}, 500);

Is there a way to continue executing a javascript function from the same point after a page postback?

I have to work on an old system here at work where there are long lists of data that i have to mark for deletion, and since this application is really old (.net 1.1 i guess) and nobody has the source, I have to do it manually by using javascript to try to automate the application interface.
Heres the process i want to automate using a bookmarklet:
on the website page, search for all the checkbox elements and set them to checked
go to the end of the page, click on the submit button and wait for the postback
click on the "next page" link on the pagination section at the bottom of the list
wait for the new page to load
repeat until there is no more "next page button".
The html is very well structured, so finding the controls to click, etc., is really not the problem, what I cannot figure out how to do is continue executing the javacript function after the page postback is done.
Does anyone know how to do something like this?
pseudocode of what i got so far, besides the WaiForThePostbackToComplete i have figured it out all the rest:
while($('#nextPageLink').length) {
var checkboxes = getCheckboxes();
checkboxes.each(click());
var submitbutton = getSubmitButton();
document.location = submitbutton.attr('href');
// im stuck here, after the postback the function stops
WaiForThePostbackToComplete();
var nextpage = getNextPageLink();
document.location = nextpagelink.attr('href');
}
You can't really restart back from a line. I don't know of any programming language that would let you start execution from a line if you didn't know which one.
What you need to do here is maintain state of what you last executed.
The simplest option would be to use a javascript cookie to keep this state.
document.cookie = 'timesRum=1; expires=Wed, 24 Jul 2013 02:47:11 UTC; path=/'
You can refer this tutorial, that will give you a few helper functions to work with cookies
You can try this:-
<% if(IsPostBack)
{%>
var nextpage = getNextPageLink();
document.location = nextpagelink.attr('href');
<%}%>

Categories

Resources