2

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.

tshepang
  • 12,111
  • 21
  • 91
  • 136
Kleptine
  • 5,089
  • 16
  • 58
  • 81

2 Answers2

4

"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;
}
Tyson
  • 968
  • 1
  • 6
  • 15
  • Okay. If ignore_user_abort() is set to true, will it still allow the user to continue leaving the page? Or will is stop them all together and keep them on it? And why the heck am I using Ajax if I could run php's through injecting an image src? Does it work exactly the same way, or is there a benfit to Ajax? Thanks. – Kleptine Aug 19 '09 at 04:27
  • Oh, ignore the question on ignore_user_abort(). I assumed it was a JS flag rather than PHP. – Kleptine Aug 19 '09 at 04:28
  • 1
    The only benefit to the XMLHttp method is that you can get a result back - in this case, you don't need any result. So, you can just inject an image. And yes, the ignore_user_abort() simply tells PHP to not abort execution if the user closes the connection. – Tyson Aug 19 '09 at 05:02
2

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.

Tyler Carter
  • 60,743
  • 20
  • 130
  • 150