Question

Jquery statement to tally total of something happening every 3.6 seconds

Asked by: nanharbison

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.

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2008-02-02 at 03:57:28ID23131825
Tags

javascript

,

all browsers

,

http://www.projecthealthychildren.org/newsite/

Topics

JavaScript

,

Scripting Languages

Participating Experts
3
Points
250
Comments
30

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. jQuery url call back messing with JS
    An expert here helped me a TON with working with jQuery and my website and got it working fine, when you click the links to the left, it loads the content via ajax but if you click the contents inside the accordion it wont load them also wont load my lightbox I have when you ...
  2. jquery chained selects
    Hello note: sorry for my english OK , I try to use a library jquery and plugin jquery chained select, but i have 2 problem: 1. how i can get data from database mysql? i post code php : ******************************PHP <?php $array = array(); if ($_GET['_name'] == 'tipglas...
  3. Select direct children with a css class in jquery
    Hello, i need to select (using jquery 1.3) "div" tags with a css class "class1" that are direct children of an element saved in a javascript variable "elem1". Something like: $("div.class1", elem1).css("color: white"); but...
  4. jQuery noConflict in WordPress, and External js Files
    Hi, I am trying to convert my HTML page into a template in WordPress. I'm banging my head agains the wall, and I'm sure this is something simple I'm just not knowledgable about. I have several jQuery features on my site. You can see it here: http://underdogwinemerchants....

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: ragerinoPosted on 2008-02-02 at 07:19:50ID: 20804592

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>

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:

Select allOpen in new window

 

by: KokoglenPosted on 2008-02-02 at 08:15:15ID: 20804817

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.

 

by: KokoglenPosted on 2008-02-02 at 09:05:29ID: 20804993

I whipped up a demo to show.  Pretty short.
http://commadot.com/jquery/cyleNumber.php

 

by: nanharbisonPosted on 2008-02-02 at 16:19:58ID: 20806665

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.

 

by: KokoglenPosted on 2008-02-02 at 17:07:09ID: 20806835

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.

 

by: nanharbisonPosted on 2008-02-02 at 17:39:55ID: 20806934

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?

 

by: KokoglenPosted on 2008-02-02 at 17:46:16ID: 20806945

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.

 

by: nanharbisonPosted on 2008-02-02 at 17:55:20ID: 20806989

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

 

by: KokoglenPosted on 2008-02-02 at 18:09:20ID: 20807061

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?

 

by: nanharbisonPosted on 2008-02-02 at 18:31:17ID: 20807149

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!

 

by: KokoglenPosted on 2008-02-02 at 18:42:49ID: 20807193

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. :)

 

by: m00003643Posted on 2008-02-04 at 13:13:24ID: 20818062

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;
	}
?>

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:

Select allOpen in new window

 

by: m00003643Posted on 2008-02-04 at 13:17:11ID: 20818095

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 ?>;

 

by: nanharbisonPosted on 2008-02-07 at 03:33:26ID: 20839896

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

 

by: nanharbisonPosted on 2008-02-08 at 04:12:02ID: 20849434

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

 

by: nanharbisonPosted on 2008-02-08 at 04:12:43ID: 20849439

I forgot to put the link to show how it is working:
http://projecthealthychildren.org/newsite/jquery/sample4.php
Nan

 

by: m00003643Posted on 2008-02-08 at 06:23:43ID: 20850279

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;
        }
?>

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:

Select allOpen in new window

 

by: nanharbisonPosted on 2008-02-17 at 08:32:08ID: 20914496

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>

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:

Select allOpen in new window

 

by: KokoglenPosted on 2008-02-17 at 11:29:25ID: 20915134

You are referencing jQuery twice.  Once with the jQuery and the other with the "latest".  Just include it once.

 

by: KokoglenPosted on 2008-02-17 at 11:34:18ID: 20915152

Also the source of this file is all messed up.
http://www.projecthealthychildren.org/newsite/jquery/jquery-latest.php
What happened to it?

 

by: KokoglenPosted on 2008-02-17 at 11:45:37ID: 20915197

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.

 

by: nanharbisonPosted on 2008-02-17 at 11:46:18ID: 20915201

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?

 

by: nanharbisonPosted on 2008-02-17 at 11:55:38ID: 31427462

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!

 

by: nanharbisonPosted on 2008-02-17 at 11:58:17ID: 20915248

oh wait, it is now just counting off seconds, not one every 3.6 seconds!

 

by: KokoglenPosted on 2008-02-17 at 12:02:04ID: 20915262

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

 

by: nanharbisonPosted on 2008-02-17 at 12:10:06ID: 20915307

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

 

by: KokoglenPosted on 2008-02-17 at 12:37:27ID: 20915494

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.

 

by: nanharbisonPosted on 2008-02-17 at 12:41:00ID: 20915526

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?

 

by: nanharbisonPosted on 2008-02-17 at 12:42:11ID: 20915538

Should I change the speed or the timeout in this code:

  $('#counter').cycle({
      fx:      'scrollDown',
      speed:    300,
      timeout:  1000,
      after:   onSlide
  });

                                              
1:
2:
3:
4:
5:
6:

Select allOpen in new window

 

by: nanharbisonPosted on 2008-02-17 at 12:43:56ID: 20915546

I changed the timeout to 3600, and now it is working!
Thanks!

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...