0

As the question stated above I am trying to set a variable in my javascript to be the value of the users username. This is how my code is set up:


function submitApproveModal(){ 
  this_file = currentFile;
  
  var approvers = "";
  if(document.getElementById('approvers').checked){
    approvers = '<?php $_SESSION['username'] ?>';
  }
  
  approveFileAjax(this_file.uid, approvers);
}

I know this is not the way for it to work and wondering how exactly can I rewrite my code so that approvers will equal the users username?

  • I would consider it bad practice to mix PHP and Javascript together. Better use `fetch` from your JS file to get values from the PHP backend. For example `fetch("getusername.php")` and then the `php` page returns the username from the session variable. Also read: https://stackoverflow.com/questions/23740548/how-do-i-pass-variables-and-data-from-php-to-javascript – Kokodoko Jun 07 '23 at 20:27
  • 1
    This will work _if your JavaScript is processed/output by PHP_. If it's an external JS file, do what @Kokodoko suggested. Otherwise, have your PHP output a JS variable snippet, e.g. `` to keep it simple, and use the `userName` variable in your function. – Markus AO Jun 07 '23 at 20:35

1 Answers1

0

You simply forgot the "echo":

approvers = '<?= json_encode($_SESSION['username']) ?>';

But as mentioned before, mixing up Javascript and PHP is a bad idea.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
MadCatERZ
  • 113
  • 7
  • this worked perfectly. –  Jun 07 '23 at 20:43
  • I like this, the only thing I'd add is to make sure to escape for JS when doing this. Maybe your username doesn't allow for `'` marks, but your whole system could break for that one weird user some day in the future. (For me, that person's name was `Rene'`, back when it was harder to use accent marks.) – Chris Haas Jun 07 '23 at 21:15