0

Any idea why this code works:

$.ajax({
    type: 'GET', 
    url: 'delete_image.php'
});

And this one doesn't:

$(window).unload(function() {
    $.ajax({
        type: 'GET', 
        url: 'delete_image.php' 
    });
});

In delete_image.php, I just have:

unlink('test.jpg');
4
  • 1
    $(window).on('unload', function(){... Commented Jul 16, 2013 at 12:46
  • @Spokey so if I'm using version 1.9.1 .unload() won't work??? Commented Jul 16, 2013 at 12:50
  • @Spokey If it's deprecated but not yet removed, it should still work. Commented Jul 16, 2013 at 12:50
  • @Ohgodwhy I just tried $(window).on('unload', function(){ but it still doesn't work Commented Jul 16, 2013 at 12:50

1 Answer 1

2

It seems that depending on what browser you are using, the browser won't wait for the ajax call to complete before the page reload. This seems to work with async:false;

$(window).unload(function() {
    $.ajax({
        type: 'GET', 
        url: 'delete_image.php',
        async:false 
    });
});

FIDDLE - Click Run in JsFiddle to unload

Sign up to request clarification or add additional context in comments.

3 Comments

i suspected that the request was not really successful and didn't arrive in the server.
as of jQuery1.8 async is deprecated it's advice to use the success callback api.jquery.com/jQuery.ajax
Thanks for your answer, first place it didn't work, then I tried with $(window).on('unload', function(){ and now it seems ok, anyway, thanks a lot!!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.