简体   繁体   中英

Javascript variable passed to PHP session in Wordpress

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:

// This is your JAVASCRIPT trackit function
function trackIt(routine, day) {
    $.post(
         '/wp-setvar.php',
         {
             routine  : routine,
             day      : day
         }, // You can add as many variables as you want (well, within reason)
         function success(data) {
             // Here we should receive, given the code below, an object
             // such that data.result is a string saying "OK".
             // Just in case you need to get back something from the server PHP.
             // Otherwise just leave this function out.
         }
    );
};

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.

<?php /** This is wp-setvar.php */

/** Set up WordPress environment, just in case */
require_once( dirname( __FILE__ ) . '/wp-load.php' );

session_id() || session_start();

nocache_headers();

// DO NOT, FOR ANY REASON, ACCESS DIRECTLY $_SESSION
// ONLY USE A VARIABLE WITHIN $_SESSION (here, "ajjx")
// OTHERWISE THIS MAY ALLOW ANYONE TO TAKE CONTROL OF YOUR INSTALLATION.
$_SESSION['ajjx'] = $_POST;

Header('Content-Type: application/json;charset=utf8');
die(json_encode(array(
    'result' => 'OK', // This in case you want to return something to the caller
))); 

Now whenever you need the session-saved variable, eg "routine", you put

<?php

  ...
  $value = '';
  if (array_key_exists('ajjx', $_SESSION)) {
       if (array_key_exists('routine', $_SESSION['ajjx']) {
           $value = $_SESSION['ajjx']['routine'];
       }
  }

Or you can define a function in your plugin,

  function ajjx($varname, $default = '') {
      if (array_key_exists('ajjx', $_SESSION)) {
           if (array_key_exists($varname, $_SESSION['ajjx']) {
               return $_SESSION['ajjx'][$varname];
           }
      }
      return $default;
  }

Then you just:

  <?php print ajjx('routine', 'none!'); ?><!-- will print routine, or "none!" -->

or

  <?php print ajjx('routine'); ?><!-- will print nothing if routine isn't defined -->

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 to wp-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 if wp-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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM