Running PHP via Ajax on unload

I am trying to run a php script when a user navigates away from a page. This is what I am currently using:

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 public function of the ajaxRequest object, but PHP won't start! Is it because it is calling it on page unload?

Also, I found an event named onbeforeunload, but I can't figure out how to get it to work if it's still available.

+2


source to share


2 answers


You need to make sure the value is ignore_user_abort()

set to true as soon as possible. If there is a default setting for it, it will be better.



+2


source


"onbeforeunload" will not work in every browser. as chacha102 says, you need to make sure the PHP script doesn't stop, the second request is terminated - ignore_user_abort()

is a good way to verify this.

Alternatively, you can try something simpler. injecting an image into a page to trigger a request may be all you need to do.



function onunload() { 
  var i = document.createElement("img");
  i.src = "ajax/cancelMatch.php?" + Math.random();
  document.appendChild(i);
  return;
}

      

+4


source







All Articles