How to pass variables and data from PHP to JavaScript?
P粉369196603
P粉369196603 2023-08-27 12:05:35
0
2
512
<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>
P粉369196603
P粉369196603

reply all(2)
P粉463811100

I usually use data-* attributes in HTML.

<div
    class="service-container"
    data-service="<?= htmlspecialchars($myService->getValue()) ?>"
>

</div>

<script>
    $(document).ready(function() {
        $('.service-container').each(function() {
            var container = $(this);
            var service = container.data('service');

            // Var "service" now contains the value of $myService->getValue();
        });
    });
</script>

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

P粉502608799

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:

  1. Use AJAX to get the required data from the server.
  2. Echo the data somewhere in the page and use JavaScript to get the information from the DOM.
  3. Echo data directly to JavaScript.

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

  • Better separation between layers - If tomorrow you stop using PHP and want to move to servlets, REST APIs, or other services, you don't need to change too much JavaScript code.
  • More readable - JavaScript is JavaScript, PHP is PHP. Without mixing the two, you get more readable code in both languages.
  • Allow asynchronous data transfer - Getting information from PHP can be time/resource consuming. Sometimes you just don't want to wait for information, load a page, and have it arrive at any time.
  • The data cannot be found directly on the tag - This means you don't have any other data in your tag, and only JavaScript can see it.

shortcoming

  • Delay - AJAX creates an HTTP request, and the HTTP request travels over the network with network latency.
  • Status - Data fetched via a separate HTTP request will not contain any information from the HTTP request that fetched the HTML document. You may need this information (for example, if the HTML document is generated in response to a form submission), and if so, you must transmit it somehow. If you have excluded embedding data in the page (which you own if you use this technology), then this limits your use of cookies/sessions which may be subject to competing conditions.

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

/* Do some operation here, like talk to the database, the file-session
 * The world beyond, limbo, the city of shimmers, and Canada.
 *
 * AJAX generally uses strings, but you can output JSON, HTML and XML as well.
 * It all depends on the Content-type header that you send with your AJAX
 * request. */

echo json_encode(42); // In the end, you need to `echo` the result.
                      // All data should be `json_encode`-d.

                      // You can `json_encode` any value in PHP, arrays, strings,
                      // even objects.

index.php (or whatever the actual page is called)

<!-- snip -->
<script>
    fetch("get-data.php")
        .then((response) => {
            if(!response.ok){ // Before parsing (i.e. decoding) the JSON data,
                              // check for any errors.
                // In case of an error, throw.
                throw new Error("Something went wrong!");
            }

            return response.json(); // Parse the JSON data.
        })
        .then((data) => {
             // This is where you handle what to do with the response.
             alert(data); // Will alert: 42
        })
        .catch((error) => {
             // This is where you handle errors.
        });
</script>
<!-- snip -->

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

  • Fast - DOM operations are generally fast and you can store and access large amounts of data relatively quickly.

shortcoming

  • Potentially non-semantic markup - Typically you'll use some sort of 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 the element 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.
  • Mess with the source code - PHP generated data is output directly to the HTML source code, which means you will get a larger and less focused HTML source code.
  • Harder to get structured data - Structured data must be valid HTML, otherwise you must escape and convert the strings yourself.
  • Tightly couple PHP with data logic - Since PHP is used for presentations, you cannot completely separate the two.

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

<!-- snip -->
<div id="dom-target" style="display: none;">
    <?php
        $output = "42"; // Again, do some operation, get the output.
        echo htmlspecialchars($output); /* You have to escape because the result
                                           will not be valid HTML otherwise. */
    ?>
</div>
<script>
    var div = document.getElementById("dom-target");
    var myData = div.textContent;
</script>
<!-- snip -->

3. Echo data directly to JavaScript

This is probably the easiest to understand.

advantage

  • Very easy to implement - takes very little time to implement and understand.
  • Do not pollute the source - Variables are output directly to JavaScript, so the DOM is not affected.

shortcoming

  • Tightly couple PHP with data logic - Since PHP is used for presentations, you cannot completely separate the two.

Implementation example

The implementation is relatively simple:

<!-- snip -->
<script>
    var data = <?php echo json_encode("42", JSON_HEX_TAG); ?>; // Don't forget the extra semicolon!
</script>
<!-- snip -->

Good luck!

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template