cs.punk Posted June 25, 2012 Share Posted June 25, 2012 Hi there. I'm trying to figure out a way to 'add' to a javascript function dynamically. Basically I'm using the JQuery library and within the $(document).ready() function I would like to add some 'code' that would change on each page generated via PHP. Basically it is just gonna be some variables that hold the 'original' values of some data. So because they can't be hard-coded, how could I 'add' them to the $(document).ready()? I could just run them as a normal script but I just thought I'd ask. Any ideas how I could go about this? Thank you! Quote Link to comment https://forums.phpfreaks.com/topic/264760-dynamically-edit-js-function-with-aid-php/ Share on other sites More sharing options...
Adam Posted June 26, 2012 Share Posted June 26, 2012 You can just echo the PHP variable into a JS variable declaration: var someVar = '<?php echo htmlspecialchars($someVar) ?>'; Added the escaping to ensure no characters within the string would break the JS syntax. Quote Link to comment https://forums.phpfreaks.com/topic/264760-dynamically-edit-js-function-with-aid-php/#findComment-1357020 Share on other sites More sharing options...
cs.punk Posted June 26, 2012 Author Share Posted June 26, 2012 You can just echo the PHP variable into a JS variable declaration: var someVar = '<?php echo htmlspecialchars($someVar) ?>'; Added the escaping to ensure no characters within the string would break the JS syntax. How would I insert this into $(document).ready() function which is loaded via <script type="text/javascript" src="js.js"></script>? I'm guessing I'm just gonna have to rewrite my system to have the $(document).ready() dynamically in each page and just echo the 'javascript code' in there. If anyone has any other ideas please let me know Quote Link to comment https://forums.phpfreaks.com/topic/264760-dynamically-edit-js-function-with-aid-php/#findComment-1357025 Share on other sites More sharing options...
Adam Posted June 26, 2012 Share Posted June 26, 2012 You could just define it before the script is included? <script type="text/javascript"> var someVar = '<?php echo htmlspecialchars($someVar) ?>'; </script> <script type="text/javascript" src="js.js"></script> Quote Link to comment https://forums.phpfreaks.com/topic/264760-dynamically-edit-js-function-with-aid-php/#findComment-1357027 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.