Solved

Passing Session variables to javascript

Posted on 2011-09-09
6
335 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
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 108

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
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 33

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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Deprecated and Headed for the Dustbin By now, you have probably heard that some PHP features, while convenient, can also cause PHP security problems.  This article discusses one of those, called register_globals.  It is a thing you do not want.  …
Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

758 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now