Scott D. Scott D. - 1 month ago 7
jQuery Question

AJAX calls are using all my webhost's memory and I/O

I am attempting to run some code that is hammering my web host's memory and I/O usage. I am unsure how I can clean up or fix this code, as this is the first time I've tried using the AJAX technology.

The JS simply needs to return the value of the PHP script it is calling every 20 seconds and display it in an empty

<div>
tag. I am very new with AJAX and I am not sure where my problem is and how to fix it.

Here is my Javascript:

<script type="text/javascript">
$(document).ready(function() {

function update() {
$.ajax({
type: 'POST',
url: 'time_hash.php',
dataType: 'text',
timeout: 20000,
success: function(data) {
$(".dispKey").html(data);
setInterval(update, 20000);
}
});// End ajax call
}// End function update()
update();

});
</script>


And my PHP script being called:

// Modify the server time to round down to the nearest 20 seconds
$modTime = (time() - (time() % 20));

// Create one-way hash from modified time
$hashToken = md5($modTime);

// Truncate hash to the first 6 characters
$dispToken = strtoupper(substr($hashToken, 0, 6));

// Display the 'generated key' -- uppercase.
echo $dispToken;


Any help would be greatly appreciated.

Answer

You are creating the interval inside your success callback, so every time your success function runs you are creating a new interval other than the one you already had and so on, so you end up with infinite intervals.

try creating the interval outside your ajax call

      function update() {
        $.ajax({
          type: 'POST',
          url: 'time_hash.php',
          dataType: 'text',
          timeout: 20000,
          success: function(data) {
            $(".dispKey").html(data); 
         }
       });// End ajax call
     }// End function update()
      setInterval(update, 20000);
Comments