Use a PHP variable in JQuery

PHP runs on the server, jquery runs on the client. If you want a PHP variable to be available to jquery (and by extension, the underlying javascript engine), you’ll have to either send the variable’s value over at the time you output the page on the server, e.g.

<script type="text/javascript">
    var my_php_var = <?php echo json_encode($the_php_var) ?>;
</script>

or retrieve the value via an AJAX call, which means you’re basically creating a webservice.

Leave a Comment