How to pass variables and data from PHP to JavaScript?
P粉369196603
2023-08-27 12:05:35
<p>I have a variable in PHP and I need its value in JavaScript code. How do I convert my variables from PHP to JavaScript? </p>
<p>My code looks like this:</p>
<pre class="brush:php;toolbar:false;"><?php
$val = $myService->getValue(); // Makes an API and database call
</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 didn't work either
myPlugin.start(<?=$val?>); // This works sometimes, but sometimes it 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 plain JavaScript.
You can read more about dataset properties here: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.dataset
There are actually several ways to do this. Some require more overhead than others, and some are considered better than others.
names not listed in order:
In this article, we will look at each of the above methods, understand the advantages and disadvantages of each method, and how to implement them.
1. Use AJAX to get the data you need from the server
This method is considered the best because your server-side and client-side scripts are completely separate .
advantage
shortcoming
Implementation example
With AJAX, you need two pages, one where PHP generates the output, and a second where JavaScript gets that output:
Get data.php
index.php (or whatever the actual page is called)
The combination of the above two files will sound an alert
42
when the file loading is complete.More reading materials
2. Echo data somewhere on the page and use JavaScript to get information from the DOM
This method is not as good as AJAX, but it still has its advantages. There is still a relative separation between PHP and JavaScript, in the sense that there is no direct PHP in JavaScript.
advantage
shortcoming
to store the information, since it's easier to get the information beyond
inputNode.value
, but doing so means there are meaningless elements in the HTML. HTML has theelement for representing data about a document, and HTML 5 introduced the
data-*
attribute for use specifically with JavaScript that can be associated with a specific element read data.Implementation example
With this, the idea is to create some kind of element that is not displayed to the user but is visible to JavaScript.
index.php
3. Echo data directly to JavaScript
This is probably the easiest to understand.
advantage
shortcoming
Implementation example
The implementation is relatively simple:
Good luck!