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
Related
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)
Hello all have a div1 which contains many other divs2,div3.....
and i want to reload div div1 after every 13 sec but without affecting the process that we are doing on other divs process may be typing messages ,viewing image etc..
can anyone please help me with this..
this is thepiece of code that i have used yet..
the code is working fine it reloads the div1 but every time it loads i need to type the message again if i have not posted it ..and some times it scroll down too..
var auto_refresh = setInterval(
function ()
{
$('#div1').load('home.php #div1').fadeIn("slow");
}, 13000);
You can pass arguments via load, Say draft for not saved and post for saved one. Suppose $('#myContent') contains your post content then the following code can be used:
$("#myDiv").load("home.php?post="+$('#myContent').val())//send posted data
OR
$("#myDiv").load("home.php?, {draft:$('#myContent').val() })//send draft data
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);
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.
On a website I'm working on, I need to load a tracking script 10 seconds after the page loads. I found a snippet to do so, but I've hit a snag. After waiting 10 seconds, the page goes white. The URL doesn't seem to change, but the page is no longer visible and the throbber starts spinning.
Here's what I'm using to load the script:
function $import(src){
var scriptElem = document.createElement('script');
scriptElem.setAttribute('src',src);
scriptElem.setAttribute('type','text/javascript');
document.getElementsByTagName('head')[0].appendChild(scriptElem);
}
// import with a random query parameter to avoid caching
function $importNoCache(src){
var ms = new Date().getTime().toString();
var seed = "?" + ms;
$import(src + seed);
}
//
// Tracker options go here...
//
setTimeout(function(){
$importNoCache("http://tracking.code/url");
}, 10 * 1000);
Is there a better way to do this?
EDIT: I stepped through the code in Firebug, and the scripts works like it should. With Firebug's debugger off, it blanks the page as I described above.
This would happen if the script calls document.write.
Can you show us the script that you're loading?
The code looks fine, so the problem is probably in the tracking code. If it contains a document.write() call, it will work fine when included normally, but wipe out the page when included after the page has finished loading.
Edit:
Yep, the tracking script does d=document, then calls d.write() later on... you won't be able to include this script after the page has finished loading.