wonder if someone could help me with a little problem. I have session values stored when my users login to my php site like this <?php echo $_SESSION['SecurityID_ContactName']; ?>.
I can reuse these values throughout the site to display the logged in users name, however I now need to store this value in an external js file which creates a form. This would then placed the logged in users name in a form field which is submitted back to mysql?
The form inside the js file has fields as such:
form += '<label>Name</label>';
form += '<input type="text" id="author" placeholder="Your name" />';
I edit this to hold the session as such:
form += '<label>Name</label>';
form += '<input type="text" id="author" value="<?php echo $_SESSION['SecurityAssist_ContactFullName']; ?> />'";
This doesn’t work, no real error as such its just removes the entire js script from the php page? Am I able to store the session value in a js file?
Kind regards
You can still store it in your HTML, for example in a
data-attribute on thebodytag.You can query it in Javascript using
getAttribute()for example:Here is a small demo
For cross-browser support you can also use jQuery (
attr()ordata()) or check this question.The other (IMO less clean) solution is to rename your Javascript file to
.php. In this, case the webserver will run it, so you can use PHP commands inside. You should send the appropriate headers in this case (Content-type: text/javascript).