Recent Posts

How to access PHP variables in JavaScript or jQuery

To have access to PHP variables in JavaScript or jQuerys sometimes you have to write something like this:

<?php echo $variable1 ?>
<?php echo $variable2 ?>
<?php echo $variable3 ?>
...
<?php echo $variablen ?>
This 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.


No comments:

Post a Comment