Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could it be, that Chrome cancels pending Ajax requests, once the browser is being redirected to another URL?

I have this function to unlock a list the user is currently editing:

function unsetLock(id) {
  $.ajax({
    type: "POST",
    url: "/ajax.php?action=unsetLock",
    dataType: 'json',
    data: "id="+ id
  });
  return true;
}

When the user navigates away from the list, I have to cancel the lock:

unsetLock(lockID);
document.location.href='/page/to/navigate/back/to.php';

However this unlock sometimes works and sometimes doesn't. I think it is because document.location.href is executed, before the ajax call has actually been sent to the server.

How can I force to send the unlock before navigating the user to the next page?

Actually I don't need to wait for the Ajax-Reply, since I want to redirect the user, whether it succeeds, or not. I just want to make sure, it is being transferred to the server.

If I place the document.location.href inside the Ajax function, it will wait for the reply.

like image 335
JochenJung Avatar asked Feb 20 '12 13:02

JochenJung


2 Answers

A really bad-mannered way to do it is to add: async: false, which will lock the browser up until the AJAX call is complete. Of course, if there is a problem and the AJAX call never completes...

It's the quickest and easiest solution to your problem, but probably not the best.

I, personally, would have the lock only last for twenty seconds (using a timestamp in the database), and send an ajax call every ten seconds to re-lock the page (if that makes sense) using setInterval(). That way the lock will unset itself a few seconds after someone leaves the page, and is good no matter what the situation (a power failure for the client wouldn't leave the page locked forever, for example).

like image 110
Grim... Avatar answered Oct 20 '22 10:10

Grim...


Perhaps I'm missing something, but why not use the success option in the Ajax call? This will execute whatever the outcome and makes sure it reaches the server.

function unsetLock(id) {
  $.ajax({
    type: "POST",
    url: "/ajax.php?action=unsetLock",
    dataType: 'json',
    data: "id="+ id,
    success: function(){
        document.location.href='/page/to/navigate/back/to.php';
    }
  });
  return true;
}
like image 24
kasimir Avatar answered Oct 20 '22 11:10

kasimir