Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set a session var using javascript and get it via php code

I have a javascript code like this :

<script type="text/javascript">

    $('#editRole').on('show.bs.modal', function (e) {  

        $roleID =  $(e.relatedTarget).attr('data-id');
        // Here I want to set this $roleID in session may be like this :
        Session['roleID'] = $roleID;                      
    });    

</script>

Then I want to get that $roleID in an other place using php code, may be like this :

<?php $roleID = Session::get('roleID'); //do something ....  ?>

Thanks

like image 449
BKF Avatar asked Dec 30 '15 20:12

BKF


People also ask

How can use session in PHP using JavaScript?

JavaScript works in the browser and PHP sessions are activated on the server, so you can't change session variables without sending a request to the server eg via a url or by submitting a form. BUT you could use sessionStorage, which is a similar principle but lives in the browser and is modifiable by javascript.

Can PHP access JavaScript session variable?

Here PHP is server-Side execution and JavaScript is Client side execution. and $_SESSION is a server-side construct.So probably you can not access that directly using JavaScript You would need to store that variable in $_COOKIE to be able to access it client-side.

How can we store JavaScript value to session variable in PHP?

In your js you can do this. var res_id = your_random_number; var res_level = your_random_number $. post("/any/url/that/contains/your/php/code", {res_id:res_id, res_level:res_level});

How can I access session variable in PHP?

Get PHP Session Variable Values From this page, we will access the session information we set on the first page ("demo_session1.php"). Notice that session variables are not passed individually to each new page, instead they are retrieved from the session we open at the beginning of each page ( session_start() ).


1 Answers

You can't set a server session variable directly from JS.

To do that you can make an AJAX call to a PHP script passing the value you want to set, and set it server side:

$('#editRole').on('show.bs.modal', function (e) {  

    $roleID =  $(e.relatedTarget).attr('data-id');

    //ajax call 
    $.ajax({
         url: "set_session.php",
         data: { role: $roleID }
    });                             
}); 

set_session.php

//preliminary code

Session::put('roleID', $request->input('role') );                      
like image 138
Moppo Avatar answered Oct 15 '22 04:10

Moppo