dplanet
dplanet

Reputation: 5403

Making jQuery wait

I have the following code in my Ajax, which executes a page reload function when time runs out.

if(time<=0)
{
    $(".time_remaining").html("Reloading the page now.");
    refresh();
}

refresh() is as follows:

function refresh() {
  $.ajax({
    type: 'POST',
    url: 'index.php',
    data: 'refresh=true',
    timeout: 0,
    success: function(data) {
        $("#current_body").html(data);
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      $("#notice_div").html('Error contacting server. Retrying in 60 seconds.');
      window.setTimeout(update, 60000);
    }
});
};

Sometimes the code doesn't update, rather it refreshes, but with the same content as before (the content definitely changes every time). I think it might be due to index.php not working quickly enough, but the Ajax is rushing to execute the

 $("#current_body").html(data); 

line. Can I make it so the Ajax delays itself between sending the data and printing the result?

Upvotes: 0

Views: 139

Answers (3)

gdoron
gdoron

Reputation: 150253

The success callback will fire only after the server returned a valid response.

 $("#current_body").html(data); // this will be executed when
                                // the "slow" server finishes it's work

So no, it has nothing to do with the server speed.

Upvotes: 2

MyStream
MyStream

Reputation: 2543

Try updating your index.php to "index.php?t="+(new Date()).getTime() to see if that busts any caching that might be causing it to return the same content.

Upvotes: 0

Ryan Lund
Ryan Lund

Reputation: 128

The success function will wait until the ajax request has finished loading. The problem you are getting may be with the cache. In your options set cache: false and it should be ok :)

/** edited to make more sense **/

Upvotes: 0

Related Questions