peirix
peirix

Reputation: 37751

jQuery click event to change php session variable

What would be the best approach to this?

Because, as I found (and it made total sense, only after having tried it :p) that you can't set a PHP variable on javascripts conditions. (duurrhh)

The only solution I can come up with is to do an AJAX call to a small PHP file that handles the session variables

elm.click(function() {
   $.post("session.php", { "hints":"off" });
   turnOffHints();
}

And then let the session.php deal with setting the new variable.

But it sorta feels like a waste to do a full http request only to set one variable in PHP...

Upvotes: 2

Views: 11462

Answers (2)

Jan Hančič
Jan Hančič

Reputation: 53931

The only other alternative is to make a "regular request" but that would be even more "wasteful".

Or maybe you could set a cookie with JavaScript and change the session when the next request comes in (you would have to check for this cookie on every request then) ...

Upvotes: 3

Pascal MARTIN
Pascal MARTIN

Reputation: 401022

Javascript (jQuery) is executed on the client-side.

PHP, and its session mecanism, is executed on the server-side.

So, to do anything related to a PHP session, you have to go to the server, doing a full HTTP Request -- you cannot stay on the client-side.

Doing an Ajax request is a way of going to the server -- works fine ;-)
What you are doing is OK (and necessary, actually), if you want to affect some session data : you don't have much of a choice, even if it feels like some kind of waste.

Upvotes: 7

Related Questions