Roman
Roman

Reputation: 13

MooTools AJAX Request on unload

i'm trying to lock a row in a db-table when a user is editing the entry. So there's a field in the table lockthat I set 1 on page load with php.

Then I was trying to unlock the entry (set it 0) when the page is unloaded. This is my approach. It works fine in IE but not in Firefox, Chrome etc.... The window.onbeforeunload works in all browsers, I tested that. They just don't do the Request BUT if I simple put an alert after req.send(); it works in some browsers but not safari or chrome. So I tried putting something else after it just so that's there's other stuff to do after the request but it doesn't work.

function test() { var req = new Request({ url: 'inc/ajax/unlock_table.php?unlock_table=regswimmer&unlock_id=', }); req.send(); alert('bla'); // ONLY WORKS WITH THIS !?!?!? }

window.onbeforeunload = test;

i've already tried different ways to do the request but nothing seems to work. And the request itself works, just not in this constellation.

ANY help would be appreciated!

Thanks

Upvotes: 1

Views: 1312

Answers (1)

Dimitar Christoff
Dimitar Christoff

Reputation: 26165

the request is asynchronous by default. this means it will fork it and not care of the complete, which may or may not come (have time to finish). by placing the alert there you ensure that there is sufficient time for the request to complete.

basically, you may be better off trying one of these things:

  1. add async: false to the request object options. this will ensure the request's completion before moving away.
  2. use an image instead like a tracking pixel.
  3. move over to method: "get" which is a bit faster as it does not contain extra headers and cookie info, may complete better (revert to this if async is delayed too much)

you can do the image like so (will also be $_GET)

new Element("img", {
    src: "inc/ajax/unlock_table.php?unlock_table=regswimmer&unlock_id=" + someid + "&seed=" + $random(0, 100000),
    styles: {
        display: "none"
    }
}).inject(document.body);

finally, use window.addEvent("beforeunload", test); or you may mess up mootools' internal garbage collection

Upvotes: 4

Related Questions