Farflame Farflame - 7 months ago 187
Javascript Question

Set session variable and change page from Jquery?

I specifically need to do things in that order - first set a session variable, but the variable comes from a data attribute in a button. After the variable is set, I want to switch to a new url, where the session variable will be retrieved.

I'm thinking that I need to use Jquery to respond to my button click, but is there a simple way from there to set the session variable and change to another url?

Or should I be looking at another way of doing this?

Answer

Session variables are on the server, they have to be set from PHP. So jQuery needs to make an AJAX request to change the variable. It can switch to the new page in the AJAX callback function.

$(".button").click(function() {
    $.ajax("something.php", { param: $(this).data("whatever") }, function() {
        window.location = "new URL";
    });
});