Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 13 of 13
  1. #1
    Regular Coder
    Join Date
    May 2004
    Posts
    407
    Thanks
    79
    Thanked 0 Times in 0 Posts

    php variable to javascript function

    Can I pass a php session variable to a javascript function?? Testing with a simple alert and it bombs out.

    alert(<?php echo $_SESSION['CURRENT_ORDER']; ?>);

  2. #2
    Master Coder Dormilich's Avatar
    Join Date
    Jan 2010
    Location
    Behind the Wall
    Posts
    5,652
    Thanks
    24
    Thanked 580 Times in 573 Posts
    check the browser's error console.
    The computer is always right. The computer is always right. The computer is always right. Take it from someone who has programmed for over ten years: not once has the computational mechanism of the machine malfunctioned.
    André Behrens, NY Times Software Developer

  3. #3
    Regular Coder
    Join Date
    May 2004
    Posts
    407
    Thanks
    79
    Thanked 0 Times in 0 Posts
    I get syntax error in log. Tried the below in my functions.js file and get the same. This is so frustrating as it seems simple when googling a solution but I'm not having any luck.


    <?php
    $variablephp = $_SESSION['EMP_ID'];
    ?>


    var variablejs = "<?php echo $variablephp; ?>" ;
    alert("category = " + variablejs);

  4. #4
    Senior Coder low tech's Avatar
    Join Date
    Dec 2009
    Posts
    1,109
    Thanks
    204
    Thanked 137 Times in 137 Posts
    try


    PHP Code:
    <?php
    // php code here
    ?>
    <!doctype html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>Test</title>
    </head>
    <body>
      <script>
        var emp_id = <?php echo '"',$_SESSION['EMP_ID'],'";'?>

        function test(){
            console.log("category = " + emp_id);
        }

        test();
     </script>
    </body>
    </html>
    0000

  5. #5
    Master Coder Dormilich's Avatar
    Join Date
    Jan 2010
    Location
    Behind the Wall
    Posts
    5,652
    Thanks
    24
    Thanked 580 Times in 573 Posts
    I would rather use json_encode() for converting PHP values to JS as a variable's data type can change.
    The computer is always right. The computer is always right. The computer is always right. Take it from someone who has programmed for over ten years: not once has the computational mechanism of the machine malfunctioned.
    André Behrens, NY Times Software Developer

  6. #6
    Senior Coder deathshadow's Avatar
    Join Date
    Feb 2016
    Location
    Keene, NH
    Posts
    2,875
    Thanks
    3
    Thanked 412 Times in 401 Posts
    Two problems, first you're not telling it that your PHP output is a string... so it's probably looking for a variable or trying to run code that doesn't exist. Second you aren't escaping the output so as to be code injection proof and/or prevent quotes and slashes from screwing things up!

    For example if your session string contained "wtf 'man' ;"

    your output would be:

    Code:
    alert(wtf 'man' :););
    Which is gibberish. What you WANT it to output in that case would be:

    Code:
    alert('wtf \'man\' :);');
    Which would be valid. (same problem if you reverse the slashes!)

    Hence the proper code should be:

    Code:
    alert('<?= addslashes($_SESSION['CURRENT_ORDER']) ?>');
    So it's creating a string, and slash escaping what needs to be slash escaped!
    Last edited by deathshadow; Jun 6th, 2018 at 08:19 AM.
    “There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies and the other way is to make it so complicated that there are no obvious deficiencies.” – C.A.R. Hoare, The 1980 ACM Turing Award Lecture
    http://www.cutcodedown.com

  7. #7
    Senior Coder low tech's Avatar
    Join Date
    Dec 2009
    Posts
    1,109
    Thanks
    204
    Thanked 137 Times in 137 Posts
    I kept getting invalid escape sequence error

    The only way I could get addslashes to work was


    PHP Code:
    <?php
    $empID 
    addslashes($_SESSION['EMP_ID']);
    $emp_id '"'.$empID.'";';
    ?>
    <!doctype html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>Test</title>
    </head>
    <body>
      <script>
        var emp_id = <?php echo $emp_id?>

        function test(){
            console.log("category = " + emp_id);
        }

        test();
     </script>
    </body>
    </html>

    I also tried to add in json_encode but I couldn't get it to work together;(


    LT
    0000

  8. #8
    Senior Coder deathshadow's Avatar
    Join Date
    Feb 2016
    Location
    Keene, NH
    Posts
    2,875
    Thanks
    3
    Thanked 412 Times in 401 Posts
    Code:
    <?php $testValue = "whatever \\'); alpha"; ?>
    <pre><?= htmlspecialchars($testValue) ?></pre>
    <script>alert('<?= addslashes($testValue) ?>');</script>
    Tests out ok. If you view-source you can see that yes, $testValue's escaped values were returned to normal when echo'd inside <pre> but are escaped properly on the alert.

    NOT that I'd write production code that way... but I'm a "one <?php and NO ?>" kind of developer.

    Code:
    <?php
    
    $testValue = 'whatever \\\');';
    
    echo '
    	<pre>', htmlspecialchars($testValue), '</pre>
    	<script>alert("', addslashes($testValue), '");</script>';
    Is how I roll.

    Just what are the contents of these $_SESSION values? Are there any CR/LF in there or anything else that could break JS string compatibility? You shouldn't need to be screwing around with extra "variables for nothing" over something this simple.

    -- edit --

    Could you post the version that DIDN'T work for you? 'Cause honestly I'd punch myself in the face before deploying what you just showed... I mean, does this work for you?

    Code:
    <!DOCTYPE html><html lang="en"><head><meta charset="utf-8">
    <title>Test</title>
    </head><body>
    <script>
    	console.log('category = "' + <?= addslashes($_SESSION['EMP_ID']) ?> + '"');
    </script>
    </body></html>
    If not there's got to be something REALLY jacked up with your session value.
    Last edited by deathshadow; Jun 6th, 2018 at 09:56 AM.
    “There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies and the other way is to make it so complicated that there are no obvious deficiencies.” – C.A.R. Hoare, The 1980 ACM Turing Award Lecture
    http://www.cutcodedown.com

  9. #9
    Senior Coder low tech's Avatar
    Join Date
    Dec 2009
    Posts
    1,109
    Thanks
    204
    Thanked 137 Times in 137 Posts
    I had this

    SyntaxError: invalid escape sequence

    source code
    <script>
    var emp_id = wtf \'man\'

    and I think the error was because of missing quotes and maybe ending semi-colon?

    adding quotes onto that string worked for me.

    my test: WHICH DID NOT WORK was this
    PHP Code:
    $_SESSION['EMP_ID'] = "wtf 'man' :)";
    $empID = addslashes($_SESSION['EMP_ID']);
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>Test</title>
    </head>
    <body>
      <script>
        var emp_id = <?php echo $empID?>

        function test(){
            console.log("category = " + emp_id);
        }

        test();
     </script>
    </body>
    </html>

    I tried this but had to change short tags to echo,. It's not playing ball for me though
    SyntaxError: invalid escape sequence



    Code:
    $_SESSION['EMP_ID'] = "wtf 'man' :)";
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>Test</title>
    </head>
    <body>
      <script>
    console.log('category = "' + <?php echo addslashes($_SESSION['EMP_ID']); ?> + '"');
    Last edited by low tech; Jun 6th, 2018 at 11:52 AM.
    0000

  10. #10
    Super Moderator
    Join Date
    May 2002
    Location
    Perth Australia
    Posts
    4,230
    Thanks
    12
    Thanked 116 Times in 114 Posts
    Code:
    var emp_id = '<?php echo $empID; ?>';
    resistance is...

    MVC is the current buzz in web application architectures. It comes from event-driven desktop application design and doesn't fit into web application design very well. But luckily nobody really knows what MVC means, so we can call our presentation layer separation mechanism MVC and move on. (Rasmus Lerdorf)

  11. #11
    Senior Coder low tech's Avatar
    Join Date
    Dec 2009
    Posts
    1,109
    Thanks
    204
    Thanked 137 Times in 137 Posts
    #firepages

    now why didn't I think if that hahaha

    +1

    LT
    0000

  12. #12
    Senior Coder deathshadow's Avatar
    Join Date
    Feb 2016
    Location
    Keene, NH
    Posts
    2,875
    Thanks
    3
    Thanked 412 Times in 401 Posts
    Also feel free to use "<?=" instead of "<?php echo" now. Only insecure outdated outmoded versions of PHP have it disabled by default. It's another of the things I use as a 'code level cutoff' so stuff I write won't even run on outdated PHP versions.

    Client side you have no control over what the user is using, server side there's ZERO huffing excuse apart from laziness, apathy, ignorance, and wishful thinking.

    They kind of blanket disabled it because <? conflicted with some pointless XML BS... thing is <?= never conflicted in the first place so it shouldn't have been lumped in with the shorter version of <?php

    Confused? That's web technologies for you. Moving target. Every time you THINK you know something they change it.
    “There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies and the other way is to make it so complicated that there are no obvious deficiencies.” – C.A.R. Hoare, The 1980 ACM Turing Award Lecture
    http://www.cutcodedown.com

  13. #13
    Senior Coder low tech's Avatar
    Join Date
    Dec 2009
    Posts
    1,109
    Thanks
    204
    Thanked 137 Times in 137 Posts
    #DS

    Yep this does exactly what you said it should do :-) Like I had any doubts haha

    It's good to know I don't need to change out short tags ----- i'm not even sure why I did that. Getting myself confused I think. Tired.


    Code:
    $_SESSION['EMP_ID'] = "wtf 'man' :)";
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>Test</title>
    </head>
    <body>
      <script>
        var emp_id = '<?= addslashes($_SESSION['EMP_ID']); ?>';
    
        function test(){
            console.log("category = " + emp_id);
        }
    
       test();
     </script>
    </body>
    </html>

    I use as a 'code level cutoff' so stuff I write won't even run on outdated PHP versions.
    I like that idea.
    Last edited by low tech; Jun 6th, 2018 at 02:30 PM.
    0000


 

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •