How to access PHP variables in JavaScript or jQuery rather than [duplicate]

Your example shows the most simple way of passing PHP variables to JavaScript. You can also use json_encode for more complex things like arrays:

<?php
    $simple="simple string";
    $complex = array('more', 'complex', 'object', array('foo', 'bar'));
?>
<script type="text/javascript">
    var simple="<?php echo $simple; ?>";
    var complex = <?php echo json_encode($complex); ?>;
</script>

Other than that, if you really want to “interact” between PHP and JavaScript you should use Ajax.

Using cookies for this is a very unsafe and unreliable way, as they are stored clientside and therefore open for any manipulation or won’t even get accepted/saved. Don’t use them for this type of interaction.
jQuery.ajax is a good start IMHO.

Leave a Comment