How to pass session id to JS?

#1

Hi All,
Can anyone help me know whether it is possible for session id to be passed in javascript file. I have ajax_file.php where I am having session start as follows:

if (!isset($_SESSION)) {
session_start();
}
$username = $_SESSION[‘emp_id’];

All I want is to know can this $username be passed in the below js file
create_request.js

> function approver(id){    
    if(id){
         var approver= $('#approver').val();
             $.ajax({
           type:'POST',
                 url:'create.php',
                data:{approver},
                success:function(data){  
                     console.log(data);
                }
             });
        }
 }
#2

PHP can echo variables anywhere.

#3
var id = "<?php echo $username; ?>" ;
console.log("shruti");
console.log(id); 
console.log("shruti"); 

I tried doing such but its not echoing my name

#4

You are doing an AJAX request, so JSON…


echo json_encode(["username" => $_SESSION['emp_id']]);
exit();

And in the client side AJAX request, you retrieve that value by the key.