Running a PHP through Ajax on Unload
-
18-09-2019 - |
Question
I'm trying to have a php script run when the user navigates away from the page. This is what I'm using currently:
function unload(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
window.location = "unsupported.html";
return false;
}
}
}
ajaxRequest.open("GET", "ajax/cancelMatch.php", true);
ajaxRequest.send(null);
}
Through FireBug, it looks like it is calling the open function of the ajaxRequest Object, but the PHP doesn't run! Is this something to do with the fact that it's calling it on the unload of the page?
Also, I've found an event called onbeforeunload, but I can't figure out how to get it working, if it still is available.
Solution
You need to make sure the ignore_user_abort()
is set to true as soon as possible. If there is a default setting for it, that would be better.
OTHER TIPS
"onbeforeunload" isn't going to work in every browser. like chacha102 says, you need to make sure the PHP script isn't stopping the second the request is terminated - ignore_user_abort()
is a good way to make sure of this.
additionally, you might want to try something simpler. injecting an image into the page to spark the request might be all you need to do.
function onunload() {
var i = document.createElement("img");
i.src = "ajax/cancelMatch.php?" + Math.random();
document.appendChild(i);
return;
}