2

I want to execute an ajax query when one user close the window. Ive got this code:

var $jQ = jQuery.noConflict();

$jQ(window).bind('unload', function() {

    $jQ.ajax({
       type: "GET",
       url: "http://www.mydomain.com/post_untrack.php"  ,
       success: function(msg){
          alert("Untrack");
       }
    });

});

I receive the "alert" event, but the script is not executed...

post_untrack.php:

<?php
mail("myemail@mydomain.com", "Script executed", "Hooray!!!");
?>

Any idea ?

Thanks!!!

Mateo
  • 177
  • 2
  • 8

3 Answers3

3

To make this work, you need to add the property

async: false

to .ajax() options object, plus you need to execute it on onbeforeunload so in jQuery

$jQ(window).bind('beforeunload',...);
jAndy
  • 231,737
  • 57
  • 305
  • 359
1

By default, ajax requests are asynchronous. So although you may start the request when the window is unloaded, it will probably get cancelled immediately and never actually sent to the user. Although you could make the request synchronous, synchronous requests really mess up the user experience by bringing the browser to a screeching halt.

More about this in this other SO question and its answers.

And of course, any ajax calls will be subject to the Same Origin Policy, if that's relevant.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

is the URL being posted to on the same domain as the page that is trying to do the ajax call?

http://en.wikipedia.org/wiki/Same_origin_policy

Harold1983-
  • 3,329
  • 2
  • 23
  • 22
  • No... im making the ajax call from myotherdomain.com. But I have a previously ajax call to the same domain (but it doesnt trigger when the page is closed) and it works fine. – Mateo Dec 28 '10 at 16:47