How to pass session id to JS?

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);
                }
             });
        }
 }

PHP can echo variables anywhere.

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

I tried doing such but its not echoing my name

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.

Sponsor our Newsletter | Privacy Policy | Terms of Service