Solved

Passing Session variables to javascript

Posted on 2011-09-09
6
350 Views
Last Modified: 2012-05-12
In an ExpressionEngine template, I'm setting a PHP session variable in a javascript file like this: (Yes, EE will parse the PHP and add plug the values to the javascript)
<?php session_start(); ?>  
function check_someone_else_result(data) {
  waiting_list_flag = false;
   <?php $_SESSION['waiting_list_flag'] = false;  ?>
  if(data.CanBuy=='YES'){
    show_for_someone_else();
  } else {
    waiting_list_flag = true;
   <?php $_SESSION['waiting_list_flag'] = true;  ?>
    $('#sm_content .oblcontent').html($('#waiting_list').html());
    $('#sm_content a.closebtn').click(function(){location.reload(true);});
    $('#sm_content a.yeswaitbtn').click(function(){show_for_someone_else();});
  } // if(data.CanBuy=='YES')
} // function check_someone_else_result

Open in new window


Now, in the show_for_someone_else() function, I'm redirecting to another page that loads another
javacript file and I'm trying to set a javascript variable to the same value that I set the session
variable to above.
<?php session_start(); ?>
   var CART_URL          = '{site_url}store/checkout/cart/';
   $(document).ready(function(){
     // attach the validationEngine to the form
     $("#voucher_form").validationEngine('attach', {
                      scroll: false
     }); // $("#voucher_form").validationEngine

     // handles the NExt button click
     $('#checkout-step-billing a').click(function(){
      $('#checkout-step-billing .voucher_form').submit();
     }); // $('#checkout-step-billing a').click
    
     // handles keypresses in all the fields in the form to submit the 
     // form when the press enter
     $("#checkout-step-billing .voucher_form input").keypress(function (e) {
      if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
        $('#checkout-step-billing .voucher_form').submit();
        return false;
      } else {
        return true;
      }
     }); // $("#checkout-step-billing .voucher_form input").keypress

     // set the wait_list_flag from the session variable
     var wait_list_flag = <?php $_SESSION['waiting_list_flag']; ?>   
   }); // $(document).ready

Open in new window

But I am not getting anything at all.

How do I need to do this?
0
Comment
Question by:EddieShipman
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
6 Comments
 
LVL 26

Assisted Solution

by:EddieShipman
EddieShipman earned 0 total points
ID: 36511329
Ah, crud, forgot to ECHO the session variable value:
var wait_list_flag = <?php echo $_SESSION['waiting_list_flag']; ?>  

Open in new window

0
 
LVL 17

Assisted Solution

by:nanharbison
nanharbison earned 160 total points
ID: 36516296
Have you tried just echoing $_SESSION['waiting_list_flag'] to see if it is set? And have you used Firebug or another debugger in a browser to see what is happening?
0
 
LVL 110

Assisted Solution

by:Ray Paseur
Ray Paseur earned 170 total points
ID: 36516322
See if this helps clarify the way the moving parts interact...
http://www.laprbass.com/RAY_temp_eddieshipman.php
<?php // RAY_temp_eddieshipman.php
error_reporting(E_ALL);


// START THE SESSION (DO THIS FIRST, UNCONDITIONALLY, IN EVERY PHP SCRIPT ON EVERY PAGE)
session_start();

// INITIALIZE THE SESSION ARRAY TO SET A DEFAULT VALUE
if (empty($_SESSION["cheese"])) $_SESSION["cheese"] = 1;

// SEE IF THE CORRECT SUBMIT BUTTON WAS CLICKED
if (isset($_POST['fred']))
{
    // ADD ONE TO THE CHEESE
    $_SESSION['cheese']++;
}
// END OF PROCESSING THE FORM



// RECOVER THE CURRENT VALUE FROM THE SESSION ARRAY (MAKES HEREDOC EASIER)
$cheese = $_SESSION['cheese'];

// CREATE THE JAVASCRIPT USING HEREDOC NOTATION
$js = <<<END_JS
<script>
alert("Cheese is $cheese");
</script>
END_JS;

// PUT THE JAVASCRIPT INTO THE BROWSER OUTPUT
echo $js;



// CREATE THE FORM USING HEREDOC NOTATION
$form = <<<ENDFORM
<html>
<head>
<title>EddieShipman Session-to-JavaScript</title>
</head>
<body>
Currently, SESSION["cheese"] contains: $cheese<br/>
<form method="post">
<input type="submit" value="increment this cheese" name="fred"  />
<input type="submit" value="leave my cheese alone" name="john" />
</form>
</body>
</html>
ENDFORM;

// PUT THE FORM INTO THE BROWSER OUTPUT
echo $form;

Open in new window

0
Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now

 
LVL 34

Assisted Solution

by:Slick812
Slick812 earned 170 total points
ID: 36516978
greetings EddieShipman, , looked at your code above, I do very much coding using exchange values between PHP and javascript, your code seems to have several invalid assumptions.  First =
waiting_list_flag = false;
   <?php $_SESSION['waiting_list_flag'] = false;  ?>
  if(data.CanBuy=='YES'){
    show_for_someone_else();
  } else {
    waiting_list_flag = true;
   <?php $_SESSION['waiting_list_flag'] = true;  ?>

I can not see your purpose or logic here, no matter what, the $_SESSION['waiting_list_flag'] will always be set to true, in PHP coding there is NO interaction between javascript and PHP, as your code seems to assume. (but I might have missed something? ?), to get javascript values into PHP values, I need AJAX or a HTML form submit.

next, , you have -
var wait_list_flag = <?php echo $_SESSION['waiting_list_flag']; ?>

if $_SESSION['waiting_list_flag'] is set to true or false (not a string), this may not output anything from PHP. I would try
var wait_list_flag = <?php if($_SESSION['waiting_list_flag']) echo 'true'; else echo 'false'; ?>;
      this is untested, but you may get the idea, javascript requires a  ;  at the end of line, you may have forgot to write

Am I getting what you are trying to do here? or am I no headed on this?
0
 
LVL 26

Accepted Solution

by:
EddieShipman earned 0 total points
ID: 36517443
@nanharbison,
  I am using Firebug but it would not let me open the javascript file to view the value because it hadn't been rendered.

@Ray,
  Thanks for the demo Ray, but due to the use of ExpressionEngine, it is a little more complicated than that. See below.

@Slick,
  Because ExpressionEngine lets you include PHP in your javascript templates, it will parse the PHP before the javascript is served to the client, hence the value being set using PHP. Adding the forgotten the echo is what makes it work.

All that being said, I did change the way I was doing things in that I created a dummy form, set the fields to the needed values and submitted it to be picked up in the resulting page. It now works exactly as I planned.

Thanks for the look, however.
0
 
LVL 26

Author Closing Comment

by:EddieShipman
ID: 36541494
The missing echo was the key, here.
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

632 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question