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:

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

In your HTML file:

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

Watch a course Learn object oriented PHP

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

<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.