简体   繁体   中英

Refreshing php script inside a div

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.

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>

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM