Andrew
Andrew

Reputation: 1167

Set a session variable when a link is clicked

I want to set a session variable to 0 when any of a certain set of links are clicked. To do this I have put the following in my javascript file:

$(window).load(function () {
    $("#hdr li a").click(function () {
        $.ajax({
            type: "POST",
            url: "clear.php",
            data: "width=0"
        });
    });
});

(Ignore data: "width=0"... I don't use this data in clear.php. I put it there because I thought maybe I had to specify a data field.)

and in the file 'clear.php' I simply have:

<?php session_start();

$_SESSION['name'] = 0;

?>

So, the idea is that when any of the links in #hdr li are clicked, the user should be taken to the page that the link points to, via clear.php, which sets the session variable to 0.

This works in some browsers (Firefox and Chrome) but not in others (e.g., Safari).

Is this the standard/correct way to implement what I want? Also, how does the browser know where to go after visiting clear.php? Somehow it works, but my first thought was that I should pass the final destination URL into clear.php, and then use "header" to move from clear.php to the final destination.

Upvotes: 1

Views: 9792

Answers (4)

kerry
kerry

Reputation: 691

I had this problem. I wanted to pass a different sql string to select different rows from a table depending on the link the user clicked on but i did not want to display the sql in a GET.

My solution was to set different session variables for each link and pass the NAME of the session variable from the link. I had several links but I have just included 2 here for the example. My code for the links was:-

<?php $_SESSION["extend_stats_sql_01"] = "";                                  
echo '<a href="view_stats_1.php?sort=name&sent=extend_stats_sql_01"> View</a>';}?> <br> 

and

<?php $_SESSION["extend_stats_sql_02"] = " Where booking_status = 'Cancelled'";                               
echo '<a href="view_stats_1.php?sort=name&sent=extend_stats_sql_02"> View</a>';}?> <br> 

My code to retrieve the values on my next page to display the list with the correct sql depending on the link was:-

$stats_sql = "SELECT id, name, activity, email, diving_date, arrival_date, checkin_date, create_date, seller FROM guests ";
$sort = $_GET['sort']; 
$sent= $_GET['sent'];
$result = $_SESSION["$sent"];
$stats_sql.= "$result"; 
$stats_sql.= " ORDER BY $sort"; 

obviously you need to start a session at the beginning of each page :-

session_start(); 

and when you have finished :-

// remove all session variables
session_unset();

// destroy the session
session_destroy(); 

Upvotes: 0

Slukehart
Slukehart

Reputation: 1037

Is Ajax required? If your re-directing the user to another page & you simply want to pass some data to that page then it may be simpler to include that data in your URL.

<a href="http://yoursite.com/interesting_page.php?new_session_variable=whatever">Link</a>

Now your php would be simple:

$_SESSION['name'] = $_GET['new_session_variable'];

Now you've removed your dependency on JavaScript, does that make sense? :)


I feel it might be worth mentioning that your approach would be appropriate in certain situations, for example: if you wanted the user to be able to mark one of the links on the page as a favourite. Rather than redirecting them to the same page and reloading the majority of the pages content you might:

<a class="favourite" data-linkid="link123" href="mylink.php">My Link</a>

// Ensure your page has finished loading aka: 'ready' (almost always)
$(document).ready(function() {

    // Listen for the click event
    $('.favourite').on('click', favoriteLink);

    // On the click - post the update via ajax and update your interface
    function favoriteLink(event) {
        event.preventDefault();

        // Lets get the link id from our data attribute
        var favourite_link = $(this).data('linkid');

        // Post that information via ajax
        $.post('ajax_handler.html', { link : favourite_link }, function(data) {

            // And finally do something with the result!
            $('.result').html(data);
        });
}

Upvotes: 3

Stphane
Stphane

Reputation: 3456

The visitor do not get to clear.php page since you are performing an ajax call.

Instead, what happens is that your browser sends a request underneath via javascript using XMLHTTPRequest object which do not break your browser behavior and as such load the page the a href points to.

As said : the ajax call is usless. You'd better include clear.php on top of your pages and test if whether or not you should set your session var, based on get param for exemple.

If you do want to keep the ajax call before the browser gets to a new page, you may attach an event handler on first common parent of your "resetting" links (event delegation) and test if you should send an ajax request to notify clear.php

Upvotes: 0

Rusty Jeans
Rusty Jeans

Reputation: 1426

My guess is this has something to do with the asynchronicity of AJAX, some browsers are properly firing the AJAX before the new link is loaded. Others might be canceling the AJAX request because the page is changing. Try preventing the default action of the anchor, and then use window.location to redirect them after the ajax call has returned.

$("#hdr li a").click(function (e) {
    var href = $(this).attr('href');
    e.preventDefault()
    $.post("clear.php", function () {
        window.location = href;
    });
});

Upvotes: 2

Related Questions