Mateo
Mateo

Reputation: 177

Ajax query when user closes the window?

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("[email protected]", "Script executed", "Hooray!!!");
?>

Any idea ?

Thanks!!!

Upvotes: 2

Views: 356

Answers (3)

T.J. Crowder
T.J. Crowder

Reputation: 1074305

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.

Upvotes: 1

jAndy
jAndy

Reputation: 236022

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',...);

Upvotes: 3

Harold1983-
Harold1983-

Reputation: 3369

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

Upvotes: 0

Related Questions