FadelMS
FadelMS

Reputation: 2037

invoke a function on leaving the current page

I tried to use the update function with onunload but the function wasn't invoked. How can invoke the update function on leaving or closing the current page? Thanks

jQuery(document).ready(function($){
    function update()
        {
            $.post('http://www.example.com/scripts/home.php');
        }

    });

Upvotes: 1

Views: 305

Answers (3)

ShankarSangoli
ShankarSangoli

Reputation: 69915

onbeforeunload event should do the trick for you. But the call shuold be synchronous to wait for the response and react to it. With sync call the browser may get hanged which will not be accepted by the user.

Upvotes: 0

Mrchief
Mrchief

Reputation: 76218

It's a bad design to do stuff onunload. You should change your design to something that doesn't rely on this event.

If you must have to, try doing your call in onbeforeunload.

Upvotes: 4

pimvdb
pimvdb

Reputation: 154858

Make in synchronous:

$.ajax({ type: "POST", async: false, url: "..." });

Users won't like it though. They should be able to close the page whenever they want.

Upvotes: 0

Related Questions