Skip to content

How to pass php variable's value to jquery

You can pass a PHP variable's value to jQuery by using the PHP variable in a JavaScript script, and then accessing it with jQuery. Here's an example:

In your PHP file:

Defining a variable in PHP

php
<?php
$my_variable = "hello";
?>

In your HTML file:

Example of using the PHP variable in a JavaScript script, and accessing via jQuery

php
<script>
var my_variable = <?php echo json_encode($my_variable); ?>;
$(document).ready(function() {
    console.log(my_variable);
});
</script>

<div class="alert alert-info flex not-prose"> Watch a course Learn object oriented PHP</div>

Alternatively you can assign the PHP variable to a data-* attribute and then use jQuery to access it like this:

Example of using the PHP variable to a data- attribute, and accessing via jQuery*

php
<div id="my-element" data-my-variable="<‌?php echo $my_variable; ?>"></div>

<script>
$(document).ready(function() {
    var my_variable = $("#my-element").data("my-variable");
    console.log(my_variable);
});
</script>

Note: json_encode is used to avoid any issues with escaping.

Dual-run preview — compare with live Symfony routes.