'How can I get user id from session in javascript?

How can I get the user id from session in javascript?

I was using this:

$( document ).ready(function() {
    var sessionUserId = '<?php $_SESSION['user_id'] ?>';
    alert (sessionUserId);
});


Solution 1:[1]

You could create your page with php extension, create an input with the value of your user id and style none to donĀ“t display on page.

<input id="userId" value="<?php $_SESSION['user_id'] ?>" style="display:none">

When page is load call the value of your input with jQuery and id.

$( document ).ready(function() {
   alert( $('#userId').val() );
   console.log('done');
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 marc_s