I am not sure if this is the best way to do it, but I have a button that when pressed it call a onClick
JS function and it passed two parameters. I want to save those two parameters on a php session, then load another page and use those values.
So, I know that if I use something like this on PAGE !:
<?php
session_start();
$message1 = "A message";
$message2 = "Another message";
$_SESSION['routineName'] = $message1;
$_SESSION['dayName'] = $message2;
?>
I can go to PAGE 2, and by using $_SESSION['routineName']
I can use that info.
So, on PAGE 1 I have that code inside the function that is called with my onClick
:
function trackIt(routine, dayName)
{
<?php
session_start();
$message1 = "A message";
$message2 = "Another message";
$_SESSION['routineName'] = $message1;
$_SESSION['dayName'] = $message2;
?>
}
I tried things like:
function trackIt(routine, dayName)
{
<?php
session_start();
$_SESSION['routineName'] = ?> routine; <?php
$_SESSION['dayName'] = $message2;
?>
}
and others, but nothing works.
And this is how I am calling the onClick (trackIt) function:
echo('<td colspan="3" style="background-color:#005673; text-align:right; padding: 4px 0px;">
<button class="btnTrack" onClick="trackIt('' . $name . '' , '' . $nameday1 . '')" >Track It!</button></td>');
What I want to do is to save both, routine and dayName, into the session.
Is it possible to save JS variables/parameters into PHP Session?
PS: I am using WordPress.
Thanks!
The PHP code you put in your files is not executed at Javascript run time, it is executed even before the page gets sent to the client. So you can’t access
$_SESSION
from anywhere within your content, you need to do that from WordPress’s code. Usually this is done via a plugin.You need to pass your Javascript variables to a server side PHP. As @Grasshopper said, the best (or at least most maintainable way) is through AJAX:
On the server, you need to create a specific file to accept the incoming variables (it would be best if you did this from a plugin, in order not to add files outside the installation: such practices are frowned upon by security scanners such as WordFence). This here below is a butcher’s solution.
Now whenever you need the session-saved variable, e.g. “routine”, you put
Or you can define a function in your plugin,
Then you just:
or
An even more butcherful solution is to add the function definition above within
wp-config.php
itself. Then it will be available everywhere in WordPress. Provided you have access towp-config.php
. Also, backup wp-config first and use a full FTP client to do it; do not use a WordPress plugin to edit it, since ifwp-config
crashes, the plugin may crash too… and you’ll find yourself in a my-can-opener-is-locked-within-a-can situation.If you don’t feel comfortable with some of the above, it’s best if you do nothing. Or practice first on an expendable WordPress installation that you can reinstall easily.