How to pass PHP variables and data to JavaScript
P粉004287665
2023-08-21 12:31:08
<p>I have a variable in PHP and I need to use its value in my JavaScript code. How can I pass my variables from PHP into JavaScript? </p>
<p>I have the following code: </p>
<pre class="brush:php;toolbar:false;"><?php
$val = $myService->getValue(); // Make API and database calls
</pre>
<p>On the same page, I have JavaScript code that needs to pass the value of the <code>$val</code> variable as a parameter: </p>
<pre class="brush:js;toolbar:false;"><script>
myPlugin.start($val); // I tried this but it didn't work
<?php myPlugin.start($val); ?> // This also failed
myPlugin.start(<?=$val?>); // This sometimes works, but sometimes fails
</script>
</pre>
<p><br /></p>
I usually use data-* attributes in HTML.
This example uses jQuery, but it can be adapted to other libraries or native JavaScript.
You can read more about the dataset attribute here: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.dataset
There are actually several ways to do this. Some methods require more overhead, and some are considered better than others.
In no particular order:
In this article, we will detail the pros and cons of each of the above methods, and how to implement them.
1. Use AJAX to get the required data from the server
This approach is considered the best because server-side and client-side scripts are completely separated .
advantage
shortcoming
Implementation example
To use AJAX, you need two pages, one where PHP generates the output, and another where JavaScript gets the output:
get-data.php
index.php (or the name of the actual page)
The combination of the above two files will pop up
42
when the file loading is completed.More reading materials
2. Echo the data to a certain location on the page and use JavaScript to get the information from the DOM
This method is less desirable than AJAX, but it still has its advantages. In a way, it's still relatively separated between PHP and JavaScript, since PHP is not used directly in JavaScript.
advantage
shortcoming
<input type=hidden>
to store the information because frominputNode.value
It's easier to get the information in, but doing so means you have a meaningless element in your HTML. HTML has the<meta>
element for document data, and HTML 5 introduces thedata-*
attribute for JavaScript-related data on specific elements.Implementation example
In this case, you need to create some kind of element that is invisible to the user but visible to JavaScript.
index.php
3. Echo data directly into JavaScript
This is probably the easiest way to understand.
advantage