to be clear, I'm not asking how to create a JS variable or function from PHP, rather I'm asking about the correct way or best practice to do so.
I have some PHP variables I need to use in JavaScript to make some modifications later, I also need to run a JS function when these variables are initialized.
The most obvious way to do this is to add a <script>
tag and enter my JS info in there, as follows:
?>
<script>
$(document).ready(function () {
var my_js_string = <?php my_php_string ?>
my_js_function();
});
</script>
<?php
That way I have a global JS var and the function runs on document.ready.
However, this feels wrong. If I need to create multiple JS variables from PHP the code would be bloated with scripts and document.ready(s) everywhere. Even when the document.ready is not necessary, initializing many JS global variables using this method makes the code so much harder to read and debug. Having JS globals is bad practice as well. Plus what if it's sensitive information? You don't want it floating around as a global that can be accessed by anyone.
Any recommendations on a better methodology?
One option I was thinking on, was the creation of events, fill up events with the information and then retrieve it on the proper .js file, creating local variables, but this could cause the same issue, many unnecessary events floating around.
Another way I thought was to create HTML elements containing the data, either in plain text, as data-
attributes or any other method. This is a good practice in some cases, but I don't think it's the best way when you have many variables or the variables contain sensitive information you don't want to show in the DOM.
If this is a duplicate answer, or you can direct me to relevant articles that address this, I would appreciate it, as I didn't know how to correctly search for this and couldn't find good resources.