Skip to content
PHP Logo

How can PHP variables be passed to a function in an HTML onclick event?

To pass PHP variables to a function in an HTML onclick event, you can use inline PHP code within the HTML element. You can echo the PHP variable value directly into the onclick event attribute. This way, when the element is clicked, the PHP variable will be passed to the function.

php
<?php
$variable = "Hello, World!";
?>

<button onclick="myFunction('<?php echo $variable; ?>')">Click me</button>

<script>
function myFunction(value) {
  alert(value);
}
</script>