Could it be that Chrome cancels pending Ajax requests as soon as the browser is redirected to a different URL?

I have this function to unlock the list that 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 goes from the list, I have to cancel the lock:

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

However, this unlocking sometimes works, and sometimes not. I think this is because document.location.href is executed before the ajax call was actually sent to the server.

How can I force unlock to go to the next page?

Actually, I do not need to wait for Ajax-Reply, since I want to redirect the user whether he is successful or not. I just want to make sure that it is being transmitted to the server.

If I put document.location.href inside the Ajax function, it will wait for a response.

+8
javascript jquery ajax
source share
2 answers

A very unfortunate way to do this: add async: false , which will block the browser until the AJAX call ends. Of course, if there is a problem and the AJAX call never ends ...

This is the fastest and easiest solution to your problem, but probably not the best.

I personally will only have a lock for twenty seconds (using the timestamp in the database) and send an ajax call every ten seconds to re-lock the page (if that makes sense) using setInterval() . Thus, the lock will turn off a few seconds after someone leaves the page, and this is good regardless of the situation (power failure for the client will not leave the page locked forever, for example).

+7
source share

Maybe something is missing for me, but why not use the success parameter in an Ajax call? This will perform any result and ensure that 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; } 
+4
source share

All Articles