How to access PHP session variables from jQuery function in a .js file?

前端 未结 7 916
轮回少年
轮回少年 2020-11-28 10:50

How to access PHP session variables from jQuery function in a .js file? In this code, I want to get \"value\" from a session variable

$(function() {
   $(\"#         


        
相关标签:
7条回答
  • 2020-11-28 11:05

    Strangely importing directly from $_SESSION not working but have to do this to make it work :

    <?php
    $phpVar = $_SESSION['var'];
    ?>
    
    <script>
        var variableValue= '<?php echo $phpVar; ?>';
        var imported = document.createElement('script');
        imported.src = './your/path/to.js';
        document.head.appendChild(imported);
    </script>
    

    and in to.js

    $(document).ready(function(){
    alert(variableValue);
    // rest of js file
    
    0 讨论(0)
  • 2020-11-28 11:10

    You cant access PHP session variables/values in JS, one is server side (PHP), the other client side (JS).

    What you can do is pass or return the SESSION value to your JS, by say, an AJAX call. In your JS, make a call to a PHP script which simply outputs for return to your JS the SESSION variable's value, then use your JS to handle this returned information.

    Alternatively store the value in a COOKIE, which can be accessed by either framework..though this may not be the best approach in your situation.

    OR you can generate some JS in your PHP which returns/sets the variable, i.e.:

    <? php
    echo "<script type='text/javascript'>
        alert('".json_encode($_SESSION['msg'])."');
    </script>";
    ?>
    
    0 讨论(0)
  • 2020-11-28 11:12

    You can pass you session variables from your php script to JQUERY using JSON such as

    JS:

    jQuery("#rowed2").jqGrid({
        url:'yourphp.php?q=3', 
        datatype: "json", 
        colNames:['Actions'], 
        colModel:[{
                    name:'Actions',
                    index:'Actions', 
                    width:155,
                    sortable:false
                  }], 
        rowNum:30, 
        rowList:[50,100,150,200,300,400,500,600], 
        pager: '#prowed2', 
        sortname: 'id',
        height: 660,        
        viewrecords: true, 
        sortorder: 'desc',
        gridview:true,
        editurl: 'yourphp.php', 
        caption: 'Caption', 
        gridComplete: function() { 
            var ids = jQuery("#rowed2").jqGrid('getDataIDs'); 
            for (var i = 0; i < ids.length; i++) { 
                var cl = ids[i]; 
                be = "<input style='height:22px;width:50px;' `enter code here` type='button' value='Edit' onclick=\"jQuery('#rowed2').editRow('"+cl+"');\" />"; 
                se = "<input style='height:22px;width:50px;' type='button' value='Save' onclick=\"jQuery('#rowed2').saveRow('"+cl+"');\" />"; 
                ce = "<input style='height:22px;width:50px;' type='button' value='Cancel' onclick=\"jQuery('#rowed2').restoreRow('"+cl+"');\" />"; 
                jQuery("#rowed2").jqGrid('setRowData', ids[i], {Actions:be+se+ce}); 
            } 
        }
    }); 
    

    PHP

    // start your session
    session_start();
    
    // get session from database or create you own
    $session_username = $_SESSION['John'];
    $session_email = $_SESSION['johndoe@jd.com'];
    
    $response = new stdClass();
    $response->session_username = $session_username;
    $response->session_email = $session_email;
    
    $i = 0;
    while ($row = mysqli_fetch_array($result)) { 
        $response->rows[$i]['id'] = $row['ID']; 
        $response->rows[$i]['cell'] = array("", $row['rowvariable1'], $row['rowvariable2']); 
        $i++; 
    } 
    
    echo json_encode($response);
    // this response (which contains your Session variables) is sent back to your JQUERY 
    
    0 讨论(0)
  • 2020-11-28 11:22

    This is strictly not speaking using jQuery, but I have found this method easier than using jQuery. There are probably endless methods of achieving this and many clever ones here, but not all have worked for me. However the following method has always worked and I am passing it one in case it helps someone else.

    Three javascript libraries are required, createCookie, readCookie and eraseCookie. These libraries are not mine but I began using them about 5 years ago and don't know their origin.

    createCookie = function(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    
    document.cookie = name + "=" + value + expires + "; path=/";
    }
    
    readCookie = function (name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
    }
    eraseCookie = function (name) {
       createCookie(name, "", -1);
    }
    

    To call them you need to create a small PHP function, normally as part of your support library, as follows:

    <?php
     function createjavaScriptCookie($sessionVarible) {
     $s =  "<script>";
     $s = $s.'createCookie('. '"'. $sessionVarible                 
     .'",'.'"'.$_SESSION[$sessionVarible].'"'. ',"1"'.')';
     $s = $s."</script>";
     echo $s;
    }
    ?>
    

    So to use all you now have to include within your index.php file is

    $_SESSION["video_dir"] = "/video_dir/";
    createjavaScriptCookie("video_dir");
    

    Now in your javascript library.js you can recover the cookie with the following code:

    var videoPath = readCookie("video_dir") +'/'+ video_ID + '.mp4';
    

    I hope this helps.

    0 讨论(0)
  • 2020-11-28 11:23

    If you want to maintain a clearer separation of PHP and JS (it makes syntax highlighting and checking in IDEs easier) then you can create jquery plugins for your code and then pass the $_SESSION['param'] as a variable.

    So in page.php:

    <script src="my_progress_bar.js"></script>
    <script>
    $(function () {
        var percent = <?php echo $_SESSION['percent']; ?>;
        $.my_progress_bar(percent);
    });
    </script>
    

    Then in my_progress_bar.js:

    (function ($) {
        $.my_progress_bar = function(percent) {
            $( "#progressbar" ).progressbar({
                value: percent
            });
        };
    })(jQuery);
    
    0 讨论(0)
  • 2020-11-28 11:24

    You can produce the javascript file via PHP. Nothing says a javascript file must have a .js extention. For example in your HTML:

    <script src='javascript.php'></script>
    

    Then your script file:

    <?php header("Content-type: application/javascript"); ?>
    
    $(function() {
        $( "#progressbar" ).progressbar({
            value: <?php echo $_SESSION['value'] ?>
        });
    
        // ... more javascript ...
    

    If this particular method isn't an option, you could put an AJAX request in your javascript file, and have the data returned as JSON from the server side script.

    0 讨论(0)
提交回复
热议问题