我应该通过ajax函数传递会话变量还是直接在脚本中访问它?

I have a page that uses an ajax function to get updates from another page.The function uses the user's id, which is retrieved from a session variable to find any updates, which is then displayed in a "Updates" div. While my script is working currently, i find myself wondering if i could retrieve the userid stored in the session variable in my Ajax page instead of passing the userid through the ajax function. Are there any advantages and/or disadvantages to passing the userid through the ajax function instead of accessing it directly in the ajax script?

My Ajax function:

function FetchUpdate()
{
    var userid= <?php echo $_SESSION['UserID'] ?>;
    $.ajax(
    {
        type:"POST",
        url:"getupdates.php",
        data:{userid:userid}
    })

    .done(function(data){
        $("#Updates").html(data);
        setTimeout(FetchUpdate,1000*60);

    })

}

Ajax page(getupdates.php)

session_start();
$userid=$_SESSION['UserID'];
//fetches updates
//echos updates

This is an example approach of your situation:

Javascript :

function fetchUpdate(){
    var data = {}
        data.command = 'getUpdate'
    $.post('getupdates.php', data, function(result){
        var r = JSON.parse(result)
        try {
            if(r.status == true){
                console.log('Success! '+r.message)
            }else{
                console.log(r.message)
            }
        }catch(e){
            console.log(result)
        }
    })
}

PHP :

<?php
if(!isset($_SESSION)){$session = new Session();}
$uid = isset($_SESSION['userID']) ? $_SESSION['userID'] : 0;

if(isset($_POST['command'])){$cmd = $_POST['command']}

switch($cmd){
    case 'getUpdate':
    // Check $uid with database here.
        if($uid > 0){
            $response['status'] = true;
            $response['message'] = 'User details have been updated.';
        }else{
            $response['status'] = false
            $response['message'] = 'Invalid user.'
        }
    break;
    // Process other commands here.
}
// Return output
echo json_encode($response);

?>

Hope this helps!

If you identify the user via the userid passed in POST, one could do an HTTP request to your AJAX script passing a falsified userid.

I think it's better to access the userid via the $_SESSION['UserID'].

By the way, in getupdates.php I can't see where you access $_POST['userid'] passed in the AJAX request (data:{userid:userid})...

I think it's better to retrieve the userid stored in the session variable in the Ajax page.

In case you send UserIds through ajax, someone could brute-force generate them and get other people private data. Note this is only an advantage if your UserIds are easier to guess than SESSID.

Moreover, you avoid sending unnecessary data.

If you want to store it on the front-end, that is unsafe as Andrea Riva said.

I think you can store it in case session miss.

I wouldn't suggest you make sending userid via ajax.