[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 698
  • Last Modified:

Jquery statement to tally total of something happening every 3.6 seconds

At the top of every page, I need to list how many children globally have died of malnutrition (one every 3.6 seconds, I know, HORRIBLE thing to think about). the old site was refreshing the page ina iframe with IE clicking every time there is a refresh, not a good solution. Can I do this with AJAX and  jquery do this? I create a session to store the variable, but I have no idea how to do the rest of this. I have started reading a book on AJAX and have read some tutorials on jquery, but I need this soon.
I am an intermediate PHP programmer, but a newbie in JS. Thank you.
0
nanharbison
Asked:
nanharbison
  • 15
  • 11
  • 3
  • +1
1 Solution
 
ragerinoCommented:
do i understand you right. you have a website that has some start variable and calcualtes the time until now in seconds and divides this number through 3.6 and this number is displayed in the browser?

why don't you do the calcualation and the displaying of the number in the browser. some kind of counter.

for this you wouldn't need a server-request every 3.6 seconds.

otherwise if you want to push information to browsers you should have a look at the comet/bayeux-procol :
http://www.cometd.com/

the code for a counter would look something like this (i don't know the jquery-framework, so i'm using document.getElementById ...)

the code is not tested. it should just give you an idea how to get this done.




<html>
	<head>
		<script type="text/javascript">
			function calcMalnutritionDeaths() {
			  var numberOfDeaths=0;
			  // calculate the number of children that have died from malnutrition until now
			  // numberOfDeaths = (now - definedDate in seconds ) / 3.6
			  return numberOfDeaths;
			}
			
			function showMalnutritionDeathsTimer() {
			  // display the updated number
			  document.getElementById("someDiv").innerHTML=calcMalnutritionDeaths() + " deaths since 01.01.1900";
			}
			
			// set the Timer to update the MalnutritionDeaths to be executed every second
			window.setInterval("showMalnutritionDeathsTimer()", 1000);
			showMalnutritionDeathsTimer();
		</script>
	</head>
	<body>
		<div id="someDiv">activate Javascript to see this counter</script>
	</body>
</html>

Open in new window

0
 
KokoglenCommented:
There is a nice plugin called the Cycle Plugin for JQuery.
http://www.malsup.com/jquery/cycle/

It's set up for images on the demo, but I use it for scrolling customer quotes (text) on marketo.com.  You can use it for this counter too.  Gives some nice options for effects too.

Use the plugin, to cycle through 2 divs with the same content, and on change, just increment the number.
0
 
KokoglenCommented:
I whipped up a demo to show.  Pretty short.
http://commadot.com/jquery/cyleNumber.php
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
nanharbisonAuthor Commented:
Thanks to ragerino and  Kokoglen for your suggestions! This was a bad time to ask this question, because I am about to be out of the country (US) for 2 weeks. I will try these suggestions when I return.
Kokoglen - how will I make this work across all the pages on the website? I am not sure how to integrate it into the session variable. I have printed out these solutions and will study them while I am away.
Thanks again, I will be back on top of this on February 16.
0
 
KokoglenCommented:
Just put the script into a counter.js file and then include the script on all your pages.
If you want it to be totally accurate, when the page loads, just declare the variable (count) with the real number off the server.  Not sure why you need to have sessions involved.
0
 
nanharbisonAuthor Commented:
I thought I needed sessions to get the time at any particular moment and subtract current time from the time the person logged onto the website. This counter has to continue working on every page that the user goes to, it keeps ticking away. Do I NOT need a session to do that? How would I get the time when the user first arrives on the website and keep that date the same, then keeping getting the current time?
0
 
KokoglenCommented:
How do you get the first count on the first page?  Just repeat that for every page.

Detail: The server would give the current starting count (it knows the current time and the current # of malnurished kids) then the browser (as Ive demonstrated) counts every 3600 milliseconds) to add one to the count.  The next page he goes to will start the process over, always with the correct server side beginning count.

I dont understand what time the user arrived has anything to do with the number of malnurished kids.

Again
1. Server renders page with current count start.
2. Client incremends every 3600 ms.
3. new page does the same thing.
0
 
nanharbisonAuthor Commented:
Sorry I didn't make this clear from the beginning, it is the number of kids who have died since the user logged onto the website. You can see this in action in the clunky version that was done in php. The website owner didn't want the page to refresh so often, so it only refreshes every 30 seconds. Nothing displays until it refreshes once unless you go to a different page. It is in the gray bar under the header.
www.projecthealthychildren.org
0
 
KokoglenCommented:
Ahh, ok, I get it.  Not the total amount of kids, just the individual tally for that user.  I would suggest a cookie.
http://www.stilbuero.de/2006/09/17/cookie-plugin-for-jquery/

This one is pretty easy to set and get.  SO some psuedo code
1. check for cookie, if it has a time , then get the time. Have the cookie expire in like 12 hours to let it reset if you want.
2. if it doesn't have one, set the cookie with the current time http://www.javascriptkit.com/jsref/date.shtml
3. subtract the cookie time from the current time.
4. get the start count for that page and set the variable.
5. then the demo works.

Does this help?
0
 
nanharbisonAuthor Commented:
but this is why I grabbed the initial time the user comes to the website, and stored it in a session variable, Some people don't accept cookies, right?
I just printed out an article on setting a persistent cookie, I have never done cookies before. I will work on this on my trip.
Thanks for your help!
0
 
KokoglenCommented:
Sure, the session would be fine too.  I dont know how to pull it out of the session personally, but if you can do that, it works.  My main contribution here is the demo to cycle on the client side. :)
0
 
m00003643Commented:
Kokoglen's solution will work well for the client side.  My current machine isn't set up to test this, but I think something like this should work for the server side (I'm assuming you're using PHP):

<?php
	session_start();
	if(isset($_SESSION['visitTime'])) {
		// if the session was already started.....
		$elapsedTime = $_SESSION['visitTime'] - time();
		$totalDeaths = $elapsedTime / 3600;  // 3.6 * 1000 milliseconds
	} else {
		// if this is a new session
		$_SESSION['visitTime'] = time();
		$totalDeaths = 0;
	}
?>

Open in new window

0
 
m00003643Commented:
Sorry, I rushed that first answer.  Replace

 $elapsedTime = $_SESSION['visitTime'] - time();

with

 $elapsedTime = time() - $_SESSION['visitTime'];

And just to be explicit, you'd then update the first line in Kokoglen's script to this:

var count = <?= $totalDeaths ?>;
0
 
nanharbisonAuthor Commented:
Thanks for this, I will try it. I am out of town with limited internet access, really expensive access. I will try to work on it though.
Nan
0
 
nanharbisonAuthor Commented:
m00003643-
The page isn't scrolling through the numbers and the numbers are not correct, but it is a start. I have to fiddle with it. Maybe PHP and javascript get the time differently/
Thanks
Nan
0
 
nanharbisonAuthor Commented:
I forgot to put the link to show how it is working:
http://projecthealthychildren.org/newsite/jquery/sample4.php
Nan
0
 
m00003643Commented:
Ahh... sorry, I've been living in Java land.... I was thinking that time() returned in milliseconds. It appears that in PHP it is only in seconds, and therefore the divide by 1000 was uncalled for.  I am also thinking that we should apply a floor() operation on the result since PHP has such loose type casting (we want to make sure we have an integer result).  Try replacing the php code with the snippet below.

I also had a few observations on the jQuery code as well... I noticed that you're appending the counter twice, like this:
  $('#counter').append("<span>" + count + "</span><span>" + count + "</span>");

This should only be:
   $('#counter').append("<span>" + count + "</span>");

I also think that the text() method will actually replace the current contents of the matched element, so you should be able to replace this:
  $(this).siblings("span").empty().text(count);
with
  $(this).siblings("span").text(count);
<?php
        session_start();
        if(isset($_SESSION['visitTime'])) {
                // if the session was already started.....
                $elapsedTime = $_SESSION['visitTime'] - time();
                $totalDeaths = floor($elapsedTime / 3.6); 
        } else {
                // if this is a new session
                $_SESSION['visitTime'] = time();
                $totalDeaths = 0;
        }
?>

Open in new window

0
 
nanharbisonAuthor Commented:
This is close to working, except the number does not advance by itself, I have to refresh the page.
http://www.projecthealthychildren.org/newsite/jquery/sample4.php. I can't figure out what I am missing, except it seems like as soon as the number comes from a php variable, it doesn't work.
Thanks.
<?php
        session_start();
        if(isset($_SESSION['visitTime'])) {
                // if the session was already started.....
                $elapsedTime = time() - $_SESSION['visitTime'];
                $totalDeaths = round($elapsedTime / 3.6);  // 3.6 * 1000 milliseconds
        } else {
                // if this is a new session
                $_SESSION['visitTime'] = time();
                $totalDeaths = 0;
        }
		
		//echo $totalDeaths;
		//echo $elapsedTime;
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 
<title>Fun with jQuery</title>
<script src='jquery.js' type='text/javascript'></script>
<script src='jquery-latest.php' type='text/javascript'></script>
<script src='jquery.cycle.php' type='text/javascript'></script>
<style type="text/css">
div {
  font: bold 18px verdana
}
 
div.sentence {
  float:left;
}
 
div#counter {
  float:left;
  height: 20px;
  width: 250px;
  padding: 1px 0px 0px 5px;
}
 
 
</style>
 
<script type="text/javascript">
var count = <?= $totalDeaths ?>;
 
$(document).ready(function(){
 
$('#counter').append("<span>" + count + "</span>");
 
  $('#counter').cycle({
      fx:      'scrollDown',
      speed:    300,
      timeout:  1000,
      after:   onSlide
  });
 
 
});
 
function onSlide() {
  count++;
  $(this).siblings("span").empty().text(count);
 
}
 
 
</script>
 
 
 
</head>
 
<body class="oneColFixCtr">
<div>Mission: To make a counter.</div><br />
 
 
<div style="position: relative;">
  <div class="sentence">The number of times I love jQuery is:</div>
  <div id="counter"></div>
</div>
<br clear="all"/><br />
 
</body>
</html>

Open in new window

0
 
KokoglenCommented:
You are referencing jQuery twice.  Once with the jQuery and the other with the "latest".  Just include it once.
0
 
KokoglenCommented:
Also the source of this file is all messed up.
http://www.projecthealthychildren.org/newsite/jquery/jquery-latest.php
What happened to it?
0
 
KokoglenCommented:
Lastly, sorry for the multiple posts.  But one more error.
$('#counter').append("<span>" + count + "</span><span>" + count + "</span>");
Line 49
I had TWO spans.  Go back and check out my source.  They are required for the cycle plugin to have more than one thing to cycle.  Basically, I am swapping the two spans and after each one moves, I add one to the other span.  If you don't have the second span, it will not have anything to cycle and no number will get added.
0
 
nanharbisonAuthor Commented:
I copied and pasted the source of that file. Should I be using that one (not messed up) instead of the other reference to jquery? I took out the reference to jquery-latest, but it is still not working
If the jquery-latest is messed up, jquery.cycle.php is probably also messed up. Is there some way I can get those pages without copy/pasting them?
0
 
nanharbisonAuthor Commented:
Someone told me to take out the second span, I just put it back and I added another include  that I think I missed - cycle-plugin.js
And it is working! This is awesome, thank you so much, Kokoglen!
0
 
nanharbisonAuthor Commented:
oh wait, it is now just counting off seconds, not one every 3.6 seconds!
0
 
KokoglenCommented:
Do you have the web developer toolbar?
https://addons.mozilla.org/en-US/firefox/addon/60

It has alot of great tools for web dev (for firefox).  One of them is to view all the javascript of a page.

Download the files here: (dont cut and paste or reference these links.  Download them and save to your web server.

http://code.google.com/p/jqueryjs/downloads/detail?name=jquery-1.2.3.pack.js#makechanges
http://www.malsup.com/jquery/cycle/jquery.cycle.all.pack.js?v2.10
0
 
nanharbisonAuthor Commented:
I will get these tools.
Meanwhile, the counter starts with the correct number when I refresh the page, but then it just ticks off the seconds, instead of advancing one every 3.6 seconds. I don't know how to fix that.
Thanks
0
 
KokoglenCommented:
WHen I view source of this page: http://projecthealthychildren.org/newsite/jquery/sample4.php, I still see double references to everything.
You need 1 jquery, 1 cycle plugin.  Update the page and try again.

0
 
nanharbisonAuthor Commented:
I removed all the extraneous references, and it is still counting the number of seconds, not increasing one every 3.6 seconds. I don't see a place where the number of seconds elapsed has been divided by 3.6, is there one?
0
 
nanharbisonAuthor Commented:
Should I change the speed or the timeout in this code:
  $('#counter').cycle({
      fx:      'scrollDown',
      speed:    300,
      timeout:  1000,
      after:   onSlide
  });

Open in new window

0
 
nanharbisonAuthor Commented:
I changed the timeout to 3600, and now it is working!
Thanks!
0

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

  • 15
  • 11
  • 3
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now