Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Passing Session variables to javascript

Posted on 2011-09-09
6
Medium Priority
?
359 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 640 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 111

Assisted Solution

by:Ray Paseur
Ray Paseur earned 680 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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 34

Assisted Solution

by:Slick812
Slick812 earned 680 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

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

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

Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

688 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