how do I "ajaxify" my php code? - php

I have divs that I want to display at specific times throughout the day. I have it working in PHP, but it requires refreshing the browser manually. I would like my script to automatically load the right div when the time is right.
Am I on the right track? Perhaps there is a jquery plugin for this sort of thing that would handle the refreshing?
Any help is greatly appreciated... Thanks!
<?php
$time = date("H\:i");
if (($time > "16:59") && ($time < "18:59")) {
echo "<div>1</div>";
}
elseif (($time > "18:59") && ($time < "20:59")) {
echo "<div>2</div>";
}
elseif (($time > "20:59") && ($time < "22:59")) {
echo "<div>3</div>";
}
else {
echo "<div id='out'><p>Outside the specified point in time.</p></div>";
}
?>

You won't need a jquery plugin to handle refreshing, you can just create a timer which checks every few minutes/seconds
#jasie was right to mention timers. He mentioned jquery timer, but you can just as well use regular javascript timers, like this (you tagged jquery, so I'll use jquery):
var timer = setInterval(function(){
var hour = (new Date()).getHours();
if (hour >= 17 && hour < 19) {
var $div = $('<div>1</div>');
} else if (hour >= 19 && hour < 21) {
var $div = $('<div>2</div>');
} else if (hour >= 21 && hour < 23) {
var $div = $('<div>3</div>');
} else {
var $div = $("<div id='out'><p>Outside the specified point in time.</p></div>");
}
$div.appendTo('body');
}, 2000); // checking every 2 seconds.
That should do the trick

I would use JQuery timer to poll every so often; when the time is right, use a $.load() to load in new information into the div on the page. You should do the time checks in Javascript, as you've done, so that you're not constantly transferring needless data between client and server.

Your backend should return a specific bit of html you want to display.
Your front-end should just be polling one specific url on the backend that returns this information.
(There are other ways to do it but this is my opinion)

As a start, using jQuery's AJAX call and a simple js timer. If page has one div with ID of "showithere", this willre-load your PHP page every 10 minutes:
<head>
<script>
​function fn () {
alert ('now');
$("#showithere").load ("http://jsbin.com/help/");
}
</script>
</head>
<body onLoad="setTimeout (fn, 600000);" >
​​​​​​​​​​​​​​​

Related

jQuery countdown with update

We are using the following countdown function on our bidding site.
setInterval(function(){
$(".countdown").each(function(){
var seconds = $(this).data('seconds');
if(seconds > 0) {
second = seconds - 1;
$(this).data('seconds', second)
var date = new Date(null);
date.setSeconds(second);
$(this).html(date.toISOString().substr(11, 8))
}
else
{
$(this).html("Finished");
alert('finished');
}
});
}, 1000);
we pass the number of seconds where we want the counter to appear (sometimes more than once on our page:
echo "<div id=\"".$auctionid."\" class=\"countdown\" data-seconds=\"".$diff."\"></div>";
So far it should be clear an it works. Now we have a situation where when someone bids somewhere on the site - the time left for auction is prolonged for 15 seconds, which is written to mysql.
$diff variable is calculated from mysql end time, and it's passed to jQuery on page load.
The question is how to check the mysql time for that auction and sync it in jQuery counter? We had the idea to maybe check every 5 seconds and after it reaches zero to make sure it's over? Any suggestions?
It should look nice to the user.
EDIT:
This is what we have so far:
$(".countdown").each(function() {
var countdown = $(this);
var auctionid = $(this).attr('id');
var interval = setInterval(function() {
var seconds = countdown.data("seconds");
if( seconds > 0 ) {
var second = --seconds;
var date = new Date(null);
date.setSeconds(second);
countdown.data("seconds", second).html(date.toISOString().substr(11, 8))
} else {
// countdown.html("Finished <img src=\"loading.gif\" class=\"tempload\">");
startUpdateingTimeFromDatabase(auctionid);
countdown.html("Finished");
clearInterval(interval);
}
}, 1000);
});
function startUpdateingTimeFromDatabase(auctionid) {
$.getJSON("timer.php?auctionid="+auctionid, function(response) {
// console.log(response.seconds);
$(".countdown#"+auctionid).data("seconds", response.seconds);
if( response.seconds > 0 ) {
// setTimeout(startUpdateingTimeFromDatabase(auctionid), 1000);
} else {
}
});
}
This simply isn't doing what we need it to do. We need to update the seconds (query startUpdateingTimeFromDatabase) every time it reaches zero. Now I think there are two approaches. First is simply return seconds via startUpdateingTimeFromDatabase function and then do everything in the main function, second is update the div via startUpdateingTimeFromDatabase. I think first will be better but I simply can't find a way to do it properly.
Any help is appreciated. Thanks.
You store the seconds left in the elements data. So why not fetch the remaining time maybe via ajax and just pass the new seconds to the elements? Within the next interval run all times will be updated.
Something like this:
$.get("yourGetRemainingTimeScript.php", {auctionId: 1}, function(response) {
$(".countdown").data("seconds", response.seconds);
});
How you check and get the remaining time is up to you. You can set the time for all everywhere again.
$(".countdown").data("seconds", 1337);
Another hint from my side: don't loop all elements with each in the setInterval. Create the intervals inside the loop once. Then your script doesn't need to search every second again over and over for the elements.
And clear the interval when it's finished.
$(".countdown").each(function() {
var countdown = $(this);
var interval = setInterval(function() {
// do your stuff ...
// when finished stop the interval
if( finished ) {
clearInterval(interval);
}
}, 1000);
});
Full working example.

cant auto submit after countdown

please help, theres 2 things i want to asking about:
with that script, the count down just show an number, iwant the countdown shown
as time format --:--:--
i cant auto submit after the countdown finish, and the count down wont stop after zero.
<script>
function timeOut(){
alert("timeout");
document.getElementById('myFormId').submit();
}
(function () {
var timeLeft = <?php echo ($data_test['TIME'] * 60) - $tb ?>,
cinterval;
var timeDec = function (){
timeLeft--;
document.getElementById('timer').innerHTML = timeLeft;
if(timeLeft === 0){
timeOut();
clearInterval(cinterval);
}
};
cinterval = setInterval(timeDec, 1000);
})();
</script>
var interval = 11; // Whatever.
function myTimer(interval){
document.getElementById('timer').innerHTML = --interval;
if (interval > 0) setTimeout(function(){myTimer(interval);}, 1000);
else document.forms['myFormId'].submit();
}
myTimer(interval);
Something along these lines. Could be a lot better, but it's really just to give you an example right here. Shouldn't be much of a hazle.
Edit:
Also see JavaScript seconds to time string with format hh:mm:ss for the formatting.

Log out automatically when there is no use of Keyboard or Mouse

When i do not use keyboard and mouse for a particular time limit (Like 10 min or 20 min) at that time it should log out User automatically from the current session. Please give me any suggestion or code in PHP.
You need javascript to detect browser events.
With jQuery, something like (untested)
var timeSinceLastMove = 0;
$(document).mousemove(function() {
timeSinceLastMove = 0;
});
$(document).keyup(function() {
timeSinceLastMove = 0;
});
checkTime();
function checkTime() {
timeSinceLastMove++;
if (timeSinceLastMove > 10 * 60) {
window.location = "path/to/logout.php";
}
setTimeout(checkTime, 1000);
}
you must set the session timeout in your code
session_set_cookie_params(3600); // sessions last 1 hour
session_start(); // do this after setting the params

Is my code a performance killer?

I am showing the value of the timer.php through AJAX in index.php . However I am concern about the performance of this, if it is a server killer if there are 30 people online, and things like this. Do you suggest me some edits?
Thank you.
index.php
<script language='JavaScript'>
setInterval( 'SANAjax();', 1000 );
$(function() {
SANAjax = function(){
$('#dataDisplay').load('timer.php');
}
});
</script>
<div id="dataDisplay"></div>
timer.php
function time_difference($endtime){
$days= (date("j",$endtime)-1);
$hours =date("G",$endtime);
$mins =date("i",$endtime);
$secs =date("s",$endtime);
$diff="'day': ".$days.",'hour': ".$hours.",'min': ".$mins.",'sec': ".$secs;
return $diff;
}
$future_time = mktime(0, 0, 0, 9, 19, 2011);
$now_time = strtotime("+2 hours");
$end_time = $future_time - $now_time;
$difference = time_difference($end_time);
if ($future_time <= $now_time ) { echo "Date reached"; } else { echo $difference; };
?>
Depends on your server specs and number of clients, this could quickly become a server-killer.
The multiple calls to a file every second will quickly put a lot of load for nothing though, so best practice calls for using a javascript timer countdown. I particularly like this one: http://stuntsnippets.com/javascript-countdown/
And for the jQuery implementation:
<script type="text/javascript">
var myDate = new Date(); //Retrieve actual date
myDate.setTime(this.getTime() + (3600 * 2)); //Add two hours
$(document).ready(function() {
$("#time").countdown({
date: myDate.toGMTString(),
onComplete: function( event ){
$(this).html("completed");
},
leadingZero: true
});
});
</script>
<p id="time" class="time"></p>
This should be enough, no more need for PHP calls and the client does everything.
By setting a setInterval for every second, you are basically saying that for 30 clients, you will be getting roughly 30 txn per second to your php server. Its hard to say its a performance killer outside of just saying you will have to handle 30tps for this simple call. I would first quesiton why you are doing this with a server side script. You could just as easily give the html file a datetime when the page loads and do the countdown with just javascript in the browser.
I use jQuery Countdown http://keith-wood.name/countdown.html to put a timer on my pages to let the user know when they are going to be logged out of the system due to inactivity.
You can bind a function to the counter expiring event.
http://code.google.com/p/jquery-countdown/ ...Simple example
http://keith-wood.name/countdown.html ...shows off all the bells and whistles...
It can be as simple as the first one or as detailed as the second!
-=Bryan

Jquery random number

I'm looking to create a simple jquery game.
It starts like this, the user enters a number in a text field.
<form>
<input type="text" id="MyNumber" value="" />
<button id="getit">Play</button>
</form>
<div id="randomnumber"></div>
After the click the play button, a series of numbers will appear in the div id randomnumber.
The objective is to click on the randomly rotating numbers in the div id randomnumber when they see the number they intered in the my number text field. If they click their number, they win.
The jquery script I have requires a button be pushed to generate the number, (I don't want a button pushed each time a new number should be generated.) The script also doesn't identify the number that was clicked, or send it to my checknumber.php page so I can store the number entered and the number picked in a database.
Any help?
this is the jquery script I have.
function IsNumeric(n){
return !isNaN(n);
}
$(function(){
$("#getit").click(function() {
var numLow = $("#lownumber").val();
var numHigh = $("#highnumber").val();
var adjustedHigh = (parseFloat(numHigh) - parseFloat(numLow)) + 1;
var numRand = Math.floor(Math.random()*adjustedHigh) + parseFloat(numLow);
if (IsNumeric(numLow)
&& IsNumeric(numHigh)
&& (parseFloat(numLow) <= parseFloat(numHigh))
&& (numLow != '')
&& (numHigh != ''))
{
$("#randomnumber").text(numRand);
} else {
$("#randomnumber").text("Careful now...");
}
return false;
});
$("input[type=text]").each(function(){
$(this).data("first-click", true);
});
$("input[type=text]").focus(function(){
if ($(this).data("first-click")) {
$(this).val("");
$(this).data("first-click", false);
$(this).css("color", "black");
}
});
});
The "Play" button is good to start the ball rolling (I'm not certain if you were thinking of removing it entirely). To generate numbers periodically, use setInterval.
$(function(){
var initialPeriod=500; // 0.5s
var generateNumIval;
function generateNum() {
var numLow = $("#lownumber").val();
var numHigh = $("#highnumber").val();
var adjustedHigh = (parseFloat(numHigh) - parseFloat(numLow)) + 1;
var numRand = Math.floor(Math.random()*adjustedHigh) + parseFloat(numLow);
if (IsNumeric(numLow)
&& IsNumeric(numHigh)
&& (parseFloat(numLow) <= parseFloat(numHigh))
&& (numLow != '')
&& (numHigh != ''))
{
$("#randomnumber").text(numRand);
} else {
$("#randomnumber").text("Careful now...");
}
}
function run(period) {
clearInterval(generateNumIval);
generateNumIval = setInterval(generateNum, period);
}
$("#getit").click(function() {
run(initialPeriod);
return false;
});
...
You can change the period (such as to increase the difficulty when the user clicks the correct number, or decreasing the difficulty when the user makes too many sequential mistakes) by calling run with a new period. If you want to change the period after generating each number, use setTimeout rather than setInterval.
To check a click on a number, register a click handler on #randomnumber that compares its val() to #MyNumber's val(). From there, take appropriate action as to whether it's a hit or miss. As Dan says, doing this for every click will create quite a bit of network traffic. Though only a small amount of data may be transmitted each time, the number of connections can cause a significant impact. Instead, have a "Stop" button and send the data if the user clicks it, or use an unload handler (one does not exclude the other).
Your server will crash and burn if you have more than a couple people playing this game. People can identify and click very fast (multiple times per second), but unless they live next to your server, you can't receive and respond to HTTP requests that fast, nor can your server handle hundreds or more per second from the multiple users.
Write the game in JavaScript and when they're done, send the totals (# of wrong clicks and # of right clicks, or whatever) to your server to save. Do your best to obfuscate how they're sent so that it's not trivial to make up scores.
There's a couple of things to look out for here. There's no reason why the random numbers can't be generated from the number the player has entered himself, or even better, a number generated by the game itself.
The way which you've done the placeholder text, using data and two event handlers is also somewhat messy. At a minimum you should be using .one to attach a one-time event handler for this, but it would be much better if you use the HTML5 placeholder attribute with a Javascript fallback.
Other than that, you're still missing significant amount of game logic in there. I won't advice you to work on this game for too long though - it's great as an exercise in working with JavaScript and jQuery, but otherwise not very worthwhile.
Oh, and just for fun, I also built my own version of this.
var hitCount = 0,
missCount = 0;
function IsNumeric(n) {
return !isNaN(n);
}
$("#getit").click(function() {
var li = [],
intervals = 0,
n = parseInt($('#MyNumber').val());
if (IsNumeric(n)) {
setInterval(function() {
li[intervals++ % li.length].text(Math.random() > .1 ? Math.floor(Math.random() * (10 + n) + (n / 2)) : n).attr('class', '');
}, 500);
}
$('#randomnumber').empty();
for (var i = 0; i < 5; i++) {
li.push($('<li />').click(function() {
var $this = $(this);
if (!$this.hasClass('clicked')) {
if (parseInt($this.text(), 10) === n) {
$this.addClass('correct');
$('#hitcount').text(++hitCount);
} else {
$this.addClass('wrong');
$('#misscount').text(++missCount);
}
}
$this.addClass('clicked');
}).appendTo('#randomnumber'));
}
return false;
});
Crude yes, but it sort of works. Have a look at it here: http://jsfiddle.net/DHPQT/
For fun..
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
var mainLoop;
$(function(){
$("#getit").click(function() {
if ($(this).attr('class') == 'start') {
$(this).attr('class','play');
$(this).html('STOP THE MADNESS!');
mainLoop = window.setInterval(function() {
var output = '';
for (var i = 0; i < 10; i++) {
var numLow = $("#lownumber").val();
var numHigh = $("#highnumber").val();
var adjustedHigh = (parseFloat(numHigh) - parseFloat(numLow)) + 1;
var numRand = Math.floor(Math.random()*adjustedHigh) + parseFloat(numLow);
output += '<div>'+numRand+'</div>';
}
$('#randomnumbers').html(output);
},250);
} else {
window.clearInterval(mainLoop);
var sweetWin = false;
$('#randomnumbers').children().each(function() {
var v = $(this).html();
if (v == $('#MyNumber').val()) {
alert('WIN!');
sweetWin = true;
$.post('127.0.0.1',{outcome:'win'});
}
});
if (!sweetWin) {
alert('FAIL!');
$.post('127.0.0.1',{outcome:'loss'});
}
$(this).attr('class','start');
$(this).html('Play');
}
});
});
</script>
</head>
<body>
Low: <input type="text" id="lownumber" value="0" />
High: <input type="text" id="highnumber" value="100" />
<input type="text" id="MyNumber" value="50" />
<button id="getit" class="start">Play</button>
<div id="randomnumbers"></div>
</body>
</html>

Categories