UKTSLiam UKTSLiam - 5 months ago 15
jQuery Question

JQuery Get page html on load and button click

Currently I have this script loading a page every 3 seconds, I'd like to change it so the script runs apon page load and then a button can also run the script to pull the details again.

<?php echo "<script>
function refresh_div() {
jQuery.ajax({
url:'example.com/urlpage',
type:'POST',
success:function(results) {
jQuery('.queue').html(results);
}
});
}

t = setInterval(refresh_div,3000);
</script>"; ?>

Answer

1.Remove t = setInterval(refresh_div,3000); so the script won't run periodically

2.Wrap code in $(document).ready() so it runs once DOM load

3.Add click event for the button

$(document).ready(function() {
  function refresh_div() {
    jQuery.ajax({
      url:'example.com/urlpage',
      type:'POST',
      success:function(results) {
        jQuery('.queue').html(results);
      }
    });
  }
  refresh_div();
  // onclick handler for button, assuming its class is 'refresh'
  $(".refresh").click(refresh_div);
}
Comments