2010/03/11

ajax setcookie failed with page reload

I have ajax to set cookie and then reload the page, the original code is some thing like the following:

$('#btn').click(function(){
  $('#btn').html('Please wait ...');
  $.get("/ajax/update.php?action=set"); //set cookie
  location.reload(true); //reload the page
});

But it failed. Looked around and figured out that the .get ajax called might not be successful before the page reload. ajax is asynchronous, so the reload function could be executing during the ajax called.

The solution is using ajax callback to make sure reload function runs after ajax call ended, see the revise code as the following,

$('#btn').click(function(){
  $('#btn').html('Please wait ...');
  $.get("/ajax/update.php?action=set", function(){
    location.reload(true);
  });
});

No comments:

Post a Comment