Search code examples
javascriptphpajaxonbeforeunload

Running a PHP through Ajax on Unload


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.