#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    16
    Rep Power
    0

    Setting a $_SESSION variable from a function


    I have a preloaded dropdown box in a form that calls a function with an onclick. It passes the ID to the function.
    I want to set a $_SESSION variable in this function so that I can use it when I call a php file from the form as an action.


    Code:
    <script>
    function setClientID(str2)
    {
    
    alert("Hello! you got into the setClientID function!");
    
    alert(str2); //this works. it shows the id of the selection from the dropdown box options. such as 1 or 2 or 3..
    
    <?php
    $_SESSION['clientID']= str2;
    echo $_SESSION['clientID'];  //this does not work. 
    ?>
    
    } 
    </script>
  2. #2
  3. Did you steal it?
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    14,056
    Rep Power
    9398
    You have to use AJAX if you want to set something in the session.

    Why can't you pass the client ID along with the rest of the form?
  4. #3
  5. Sarcky
    Devshed Supreme Being (6500+ posts)

    Join Date
    Oct 2006
    Location
    Pennsylvania, USA
    Posts
    10,908
    Rep Power
    6351
    Remember, PHP and JavaScript are two unrelated languages running on different computers. They don't just "see" each other's data. Each PHP script requires EVERY piece of information it needs to be specifically handed to it, or it will have to get that information specifically from a data store of some sort. You seem to be expecting PHP variables to somehow have access to JavaScript variables in real-time. That's not how it works. Your PHP code is dead before any of your JavaScript code begins to run. JS needs to invoke another PHP script if you want PHP to act again.

    The new user guide covers more.

    Comments on this post

    • dmittner agrees
    HEY! YOU! Read the New User Guide and Forum Rules

    "They that can give up essential liberty to obtain a little temporary safety deserve neither liberty nor safety." -Benjamin Franklin

    "The greatest tragedy of this changing society is that people who never knew what it was like before will simply assume that this is the way things are supposed to be." -2600 Magazine, Fall 2002

    Think we're being rude? Maybe you asked a bad question or you're a Help Vampire. Trying to argue intelligently? Please read this.
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    4
    Rep Power
    0
    The session value will not be ready to use til you refresh the page.

    Remember php is a server side scripting language so php sets the session but since the page is already loaded it is not usable till the next page load.

    So you woul have to set the session, but for the rest of that page use the variable you set the session with.

    example
    PHP Code:
    $myval "some value";
    $_SESSION['myval'] = $myval;
    //for the rest of this page use $myval
    echo $myval
    On any other page after you have set the value the session value will be available.
    Ray
  8. #5
  9. Sarcky
    Devshed Supreme Being (6500+ posts)

    Join Date
    Oct 2006
    Location
    Pennsylvania, USA
    Posts
    10,908
    Rep Power
    6351
    Originally Posted by craygo
    The session value will not be ready to use til you refresh the page.

    Remember php is a server side scripting language so php sets the session but since the page is already loaded it is not usable till the next page load.

    So you woul have to set the session, but for the rest of that page use the variable you set the session with.

    example
    PHP Code:
    $myval "some value";
    $_SESSION['myval'] = $myval;
    //for the rest of this page use $myval
    echo $myval
    On any other page after you have set the value the session value will be available.
    Ray
    This is not true and not really relevant to the original question anyway.
    Last edited by ManiacDan; July 25th, 2013 at 09:51 AM.
    HEY! YOU! Read the New User Guide and Forum Rules

    "They that can give up essential liberty to obtain a little temporary safety deserve neither liberty nor safety." -Benjamin Franklin

    "The greatest tragedy of this changing society is that people who never knew what it was like before will simply assume that this is the way things are supposed to be." -2600 Magazine, Fall 2002

    Think we're being rude? Maybe you asked a bad question or you're a Help Vampire. Trying to argue intelligently? Please read this.
  10. #6
  11. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    4
    Rep Power
    0
    It is relevant. Even If you use Ajax to assign the session variable from another php script, the session variable is not available to the page that is currently loaded because php has already parsed the current page.

    You can do this with Ajax. even though you cannot echo it on the current page, once you set the variable with Ajax all future forms and pages will have access to the session variable.

    example;
    1. Page loads(session variable is not set)
    2. run Ajax to set variable(Since ajax set the variable it is not available on current page because page has already been parsed by php)
    3. Submit form(once submitted the session variable will be available for use when processing form or for any future pages loaded)

    Also you can use php variable in your javascript if you echo the javascript within php tags
    PHP Code:
    echo '<script>
    function setClientID('
    .$_SESSION['str2'].')
    {

    alert("Hello! you got into the setClientID function!");

    alert(str2); //this works. it shows the id of the selection from the dropdown box options. such as 1 or 2 or 3..


    </script>'

    Granted as I said the SESSION variable should be set before the page has loaded completely.

    Ray
  12. #7
  13. No Profile Picture
    Contributing User
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Dec 2004
    Posts
    2,987
    Rep Power
    375
    in one of my page, i am setting towards the top

    $_SESSION['something'] = $_POS..

    then use the session underneath and it seems to work.

    I was also under the impression previously that you have to refresh the page, this was evident when i was setting a SESSION['eror_message'] which wouldnt display until i refreshed..
  14. #8
  15. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,959
    Rep Power
    1014
    This refresh stuff is nonsense, and it would be great if craygo stopped confusing people.

    $_SESSION is an array like any other PHP array. If you put a value into it, then it's in the array -- that's it. Try it and you'll see.
    The 6 worst sins of security ē How to (properly) access a MySQL database with PHP

    Why canít I use certain words like "drop" as part of my Security Question answers?
    There are certain words used by hackers to try to gain access to systems and manipulate data; therefore, the following words are restricted: "select," "delete," "update," "insert," "drop" and "null".
  16. #9
  17. Sarcky
    Devshed Supreme Being (6500+ posts)

    Join Date
    Oct 2006
    Location
    Pennsylvania, USA
    Posts
    10,908
    Rep Power
    6351
    It is relevant. Even If you use Ajax to assign the session variable from another php script, the session variable is not available to the page that is currently loaded because php has already parsed the current page.
    For the second time, this is not true. You are saying untruths. Falsehoods. Misinformation.

    It may be relevant to ajax/php in general, but OP needs to understand what they are first before we dive into session scope.
    HEY! YOU! Read the New User Guide and Forum Rules

    "They that can give up essential liberty to obtain a little temporary safety deserve neither liberty nor safety." -Benjamin Franklin

    "The greatest tragedy of this changing society is that people who never knew what it was like before will simply assume that this is the way things are supposed to be." -2600 Magazine, Fall 2002

    Think we're being rude? Maybe you asked a bad question or you're a Help Vampire. Trying to argue intelligently? Please read this.
  18. #10
  19. Did you steal it?
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    14,056
    Rep Power
    9398
    It looks like you guys aren't speaking the same language:

    Fact: in the current browser window/tab with the webpage where the Javascript is running, the session variable is not set/not set correctly. Hence the whole point of this thread.
    Fact: you can use AJAX to set a session variable.
    Fact: setting it won't affect the currently-rendered webpage because it's already rendered.
    Fact: in one bit of PHP code you can both set the session variable and use it without needing the original variable.
    PHP Code:
    $myval "some value"
    $_SESSION['myval'] = $myval
    //for the rest of this page use $myval or $_SESSION['myval']
    echo $myval;
    echo 
    $_SESSION['myval']; // also works 
    There are also varying ways the term "the page" is being used:
    - The PHP script and its code
    - The output of said script
    - The output of said script as well as any Javascript/AJAX executing on its behalf
    Last edited by requinix; July 25th, 2013 at 01:42 PM.
  20. #11
  21. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    4
    Rep Power
    0
    I know the session is an array like any other. And it is available on the current page. Excuse me if I misled anyone. But He said he wants to set it through a javascript function. In this case he could not view that session variable until a page refresh.

    If I am wrong please show me code which proves it.
    here is my proof.

    sessiontest.php
    PHP Code:
    <?php
    session_start
    ();
    ?>
    <!DOCTYPE html>
    <html>
    <head>
      <title>Hello!</title>
    <script type="text/javascript" src="js/jquery-1.8.2.min.js" /></script>
    <script type="text/javascript">
    jQuery(document).ready(function($) {
      $('#drop_1').change(function(){
        var drop_val = $(this).val();
        $.get("addsession.php?drop_val="+drop_val, function(response){
            data = jQuery.parseJSON(response);
            var result = data.message;
            alert(result);
        });
        });
    });
    </script>
    </head>

    <body>
    <select name="drop" id="drop_1">
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
      <option value="4">4</option>
    </select>
    <?php
    echo "Session = ".$_SESSION['drop_1'];
    ?>

    </body>
    </html>
    addsession.php
    PHP Code:
    <?php
    session_start
    ();
    $json = array("message" => $_GET['drop_val']);
    $_SESSION['drop_1'] = $_GET['drop_val'];
    echo 
    json_encode($json);
    ?>
    You will get an error the first time you open sessiontest.php. Once you change the value the Ajax will set the session value with addsession.php. After the alert you will see that session value in not available. refresh the page and it will now be there.

    Maybe I misunderstood what he wanted to do but this is what I thought he wanted to do.

    I also apologize for my first post Saying it is not available on the current page where it was set.

    Ray
  22. #12
  23. Sarcky
    Devshed Supreme Being (6500+ posts)

    Join Date
    Oct 2006
    Location
    Pennsylvania, USA
    Posts
    10,908
    Rep Power
    6351
    Your initial code example and definition of the session was definitely wrong.

    The bigger question of what constitutes "a page" and what "views" means is approaching philosophical.

    If you're saying somePage.php relies on a session value which is not set, and somePage.php prints out a snippet of JS that uses ajax to set that same session value using setSession.php, then yes, somePage.php doesn't have access to that session value when it's first drawn and must be refreshed for the PHP code on that page to see that particular value. BUT, "the page" as most people understand it is still very much in control of the data. Your code would produce an error, that's true. PHP can't time travel. However, "the page" is where data is displayed and "the page" is what originates this AJAX call. Your modified code where "the page" has access to the data WITHOUT refreshing:

    PHP Code:
    <?php 
    session_start
    (); 
    ?> 
    <!DOCTYPE html> 
    <html> 
    <head> 
      <title>Hello!</title> 
    <script type="text/javascript" src="js/jquery-1.8.2.min.js" /></script> 
    <script type="text/javascript"> 
    jQuery(document).ready(function($) { 
      $('#drop_1').change(function(){ 
        var drop_val = $(this).val(); 
        $.get("addsession.php?drop_val="+drop_val, function(response){ 
            data = jQuery.parseJSON(response); 
            var result = data.message; 
            document.getElementById('TheSessionData').innerHTML = result;
            alert(result); 
        }); 
        }); 
    }); 
    </script> 
    </head> 

    <body> 
    <select name="drop" id="drop_1"> 
      <option value="1">1</option> 
      <option value="2">2</option> 
      <option value="3">3</option> 
      <option value="4">4</option> 
    </select> 

    Session = <span id="TheSessionData">
    <?php
    if ( isset($_SESSION['drop_1']) ){ 
      echo 
    $_SESSION['drop_1']; 
    }
    ?> 
    </span>
    </body> 
    </html>
    Now "the page" has access to the data without refreshing.

    And the initial comment and code snippet about the session is still wrong. You can both set a session variable and use that variable in the same page.
    HEY! YOU! Read the New User Guide and Forum Rules

    "They that can give up essential liberty to obtain a little temporary safety deserve neither liberty nor safety." -Benjamin Franklin

    "The greatest tragedy of this changing society is that people who never knew what it was like before will simply assume that this is the way things are supposed to be." -2600 Magazine, Fall 2002

    Think we're being rude? Maybe you asked a bad question or you're a Help Vampire. Trying to argue intelligently? Please read this.
  24. #13
  25. Did you steal it?
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    14,056
    Rep Power
    9398
    How about we just not call it the "page" anymore? There's the PHP, the AJAX, and the HTML.


    So right: the HTML on the page does not have the session value so if you want to change the HTML (without using Javascript) then you have to refresh the page, at which point the PHP rendering it will have the value and can change what it outputs accordingly. Additionally if it wasn't clear, after the AJAX that results in the value being set, PHP scripts invoked by AJAX can access the new value - you don't have to literally reload the webpage before PHP can access the value.

    But the use case as I understand it is that the value needs to be set before the form can be submitted, as the target PHP script of that form needs the session value set. It's not a matter of reloading a page but about submitting data somewhere (which could be the same script that just executed). That's why I asked about whether it was possible to just put the new value in the form being submitted; it may not be if the session value needs to be used before the form is processed.
  26. #14
  27. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    16
    Rep Power
    0
    Good discussion. I learned a lot and was able to get to where I needed to go with this one. Thanks again!

IMN logo majestic logo threadwatch logo seochat tools logo