Skip to content

Instantly share code, notes, and snippets.

@Draphar
Last active July 17, 2018 21:09
Show Gist options
  • Save Draphar/88600339d066cd6fb9e20f39fdcae72f to your computer and use it in GitHub Desktop.
Save Draphar/88600339d066cd6fb9e20f39fdcae72f to your computer and use it in GitHub Desktop.
Easy method to pass server side variables to inline or extern JavaScript
var text = document.currentScript.getAttribute('data-variable'); // text is now 'Lorem ipsum dolor sit amet'
<?php
/* Using PHP for this example. You can use any server side language which can output something to the site.
* Made by Draphar
*/
$variable='Lorem ipsum dolor sit amet'; // any value which can be transformed into a string
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>
var text = "<?php echo htmlentities($variable);?>"; // easy for inline scripts
</script>
<script src="extern.js" data-variable="<?php echo htmlentities($variable);?>"></script>
</head>
<body>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment