Passing PHP variable into JavaScript [duplicate]
I've a PHP session variable, $_SESSION['user']
, alive throughout the session. In the head section, I've my JavaScript file included, scripts.js
.
How do I pass the session variable into the JavaScript file if I want something like the following.
$.("#btn').click (
function() {
alert('<?php echo $_SESSION['user']; ?>');
}
)
As the <?php ?>
isn't recognized in the JavaScript file, the code above doesn't work. So I've to put i开发者_JAVA技巧n the PHP file itself, but how do I keep it in the JavaScript file?
In your PHP file you could set your user as a global varibale:
<script type="text/javascript">
var ptamzzNamespace = {
sessionUser : '<?php echo $_SESSION['user']; ?>'
}
</script>
Include this before including your external JavaScript code.
Then in your JavaScript file you can use it:
$.("#btn').click (
function() {
alert(ptamzzNamespace.sessionUser);
}
)
Additionally:
If you're not sure if your session varibale can contain quotes itsself, you can use addslashes()
to fix this problem:
<?php echo addslashes($_SESSION['user']); ?>
even if this will maybe produce something you don't really want to display (because it produces a string with slashes) it will help that your code will not fail. (Thanks to Artefacto)
Would this be an option for you?
Set the userID (in PHP) in an input type hidden in your file. In your JavaScript code you can read the hidden input types value.
You could set your server up to parse .js files as PHP. For example, in Apache config or .htaccess file:
<FilesMatch "scripts.js">
AddHandler application/x-httpd-php5 .js
</FilesMatch>
try with below logic
print ' <script type="text/javascript" language="javascript">
function checkForm()
{
var username = "'.$_SESSION['user'].'";
if( username == '')
{
alert('No Times selected');
return false;
}
}
</script>';
Parse the included JavaScript file as PHP
Create a .htaccess file in you JavaScript directory and add the following line.
AddHandler php-cgi .js
<?php ?>
tags till now be recognized by your JavaScript file.
Use Ajax to fetch the user ID
Create a file called getID.php which only echoes the users ID. Then in your JavaScript file you can use the following code.
$.get('getID.php', function(uid) {
alert('User ID is:' + uid);
});
Create a script tag before including the JavaScript printing user ID.
<script type="text/javascript">
userID = <?php echo $_SESSION['user']; ?>;
</script>
You will now have access to the users ID using variable userID.
精彩评论