0

I am currently using the following script to refresh my messages.php in a div with a timeinterval of 60 seconds.

<script> jQuery().ready(function(){ setInterval("getResult()",60000); }); function getResult(){ jQuery.post("messages.php",function( data ) { jQuery("#msgs").html(data); }); } </script> <div id="msgs"> </div> 

My current problem is that the echo of the php file displays for the first time after the 60 seconds passed. Then it refreshes every 60 seconds. I need to get the code to load at the start of launching the page.

3
  • 1
    so, what you already achieve? where u stuck? Commented Feb 11, 2015 at 8:45
  • 1
    jQuery(getResult);would call it once document is ready. FYI, this is preferred syntax: setInterval(getResult, 60000); avoiding string evaluation Commented Feb 11, 2015 at 8:48
  • just add getResult(); BEFORE your setInterval, so that it will be executed once and, then, executed each 60 seconds Commented Feb 11, 2015 at 8:48

4 Answers 4

1

Call getResult() on DOM Ready as well

<script> jQuery().ready(function(){ getResult(); setInterval("getResult()",60000); }); function getResult(){ jQuery.post("messages.php",function( data ) { jQuery("#msgs").html(data); }); } </script> <div id="msgs"> </div> 
Sign up to request clarification or add additional context in comments.

1 Comment

missing semicolon after getResult().
1

I would just use a setTimeout every time:

<script> jQuery().ready(function() { function getResult() { $('#msgs').load('messages.php', {}); setTimeout(getResult, 60000); } getResult(); } </script> <div id="msgs"></div> 

Alternative with re-fire in the callback (suggestion of A. Wolff, in case messages.php takes long to complete):

<script> jQuery().ready(function() { function getResult() { $('#msgs').load('messages.php', {}, function() { setTimeout(getResult, 60000); }); } getResult(); } </script> <div id="msgs"></div> 

2 Comments

Good call on passing data to load method and using a timeout, even i'd use the complete load method callback, just in case the request takes more than 60 sec to complete
Nice idea. I'll add an alternative based on your suggestion.
0
<script> jQuery().ready(function(){ getResult(); setInterval("getResult()",60000); }); function getResult(){ jQuery.post("messages.php",function( data ) { jQuery("#msgs").html(data); }); } </script> <div id="msgs"> </div> 

Use this code..

Comments

0

In order to get data on page load, call getResult() on DOM ready event as shown below :-

<script> jQuery().ready(function(){ getResult(); //it will get data as soon as page is loaded. setInterval("getResult()",60000); // it will refresh #msgs after every 1 min. }); function getResult(){ jQuery.post("messages.php",function( data ) { jQuery("#msgs").html(data); }); } </script> <div id="msgs"> </div> 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.