views:

414

answers:

3

When a link is clicked, I want to clear the php session before redirecting to the destination page.

The way I thought of doing it is by loading a php script that clears the session with ajax in the origin page and once that script has loaded, to redirect to the destination page.

Here is the code I have:

$(document).ready(function() {
    $("a").click(function(){
        var clearSession = "clearsession.php";  
        $("#content").load(clearSession,"");
    });
});

<a href="destination.html">

Currently it seems to follow the link before the php script completes loading.

A few guidelines :

  1. You can't make the link point to any other page than "destination.html"
  2. You can't add variables to the destination page either (destination.html?clear)
+2  A: 

Use the load callback so you can execute the redirection after you receive a response.

$(document).ready(function() {
    $("a").click(function(){
        var clearSession = "clearsession.php";  
        $("#content").load(clearSession,"",function(){
            window.location = $(this).attr("href");
            return false;
        });
    });
});

<a href="destination.html">
jjclarkson
Thank you very much! I thought of that but couldn't seem to get it right. Works great.
Enkay
A: 

Why not just redirect to clearsession.php?link=destination.html, which clears the session and then re-redirects to the desired URL?

lod3n
A: 
$(document).ready(function() {
    $("a").click(function(){
        var clearSession = "clearsession.php";  
        $("#content").load(clearSession,"");
        return false;
    });
});

With "return false;", the browser won't follow the link.

Daniel S