Last active
August 29, 2015 14:22
-
-
Save spragucm/b50f1f4b1fd584edb549 to your computer and use it in GitHub Desktop.
Call JavaScript Function from PHP with parameters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
echo "<p>The following safely passes data from php to a function in JavaScript</p>"; | |
$myname = 'MyName'; | |
$yourname = 'YourName'; | |
//Data that is going to be passed into the JavaScript function. Try to keep all vars together so | |
//that it's easier to track down the php/javascript interaction | |
$jsdata = array( | |
'input' => $myname, | |
'array_input' => array( | |
'name' => $yourname | |
), | |
); | |
?> | |
<!--This JS can be here or a separate file since all it's doing is defining a function in the JS space'--> | |
<script> | |
function callAlert(text){ | |
alert(text); | |
} | |
</script> | |
<!--This JS must be defined with the php since it's using previously defined php variables --> | |
<script> | |
var JSDATA = <?=json_encode($jsdata, JSON_HEX_TAG | JSON_HEX_AMP )?>; | |
//Prompt using a single var | |
callAlert(JSDATA.input) | |
//Prompt using a var from a nested array | |
callAlert(JSDATA.array_input.name); | |
</script> | |
<?php | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment