-1

Suppose you are in a php file and you want to run a javascript function that has both javascript and php inside of it. How would you go about doing this? Ex:

<?php
<script>
function myFunction(){
// php code
document.write("Hello World!");
}
</script>
?>

I know I can easily make a php function for this particular code, but just for future reference, I would like to know how to do this.

I apologize if this has been answered before but it seemed difficult to word in google search.

1 Answers1

0

The PHP code has to output text that is valid inside the javascript. Something like this.

<?php
<script>
function myFunction(){
// php code
    var message = "<?php echo "My alert message"; ?>";
    window.alert(message);
}
</script>
?>
André Morales
  • 478
  • 3
  • 6
  • Don't forget to use `json_encode()` around any variable data so that things are escaped properly! – Brad Mar 25 '15 at 03:20