search

Home  >  Q&A  >  body text

How to pass PHP variables and data to JavaScript

<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>
P粉004287665P粉004287665491 days ago476

reply all(2)I'll reply

  • P粉893457026

    P粉8934570262023-08-22 09:30:13

    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 native JavaScript.

    You can read more about the dataset attribute here: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.dataset

    reply
    0
  • P粉517090748

    P粉5170907482023-08-22 09:17:08

    There are actually several ways to do this. Some methods require more overhead, and some are considered better than others.

    In no particular order:

    1. Use AJAX to get the required data from the server.
    2. Echo the data to a location on the page and use JavaScript to get the information from the DOM.
    3. Echo data directly into JavaScript.

    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

    • Better separation between layers - If tomorrow you stopped using PHP and wanted to move to servlets, REST APIs, or other services, you wouldn't need to change much of your JavaScript code.
    • Easier to read - JavaScript is JavaScript, PHP is PHP. By not mixing the two, you get more readable code.
    • Allow asynchronous data transfer - Getting information from PHP can be time/resource consuming. Sometimes you just don't want to wait for information, load the page, and then get it when it arrives.
    • Data does not appear directly in the markup - This means your markup remains clean without any extra data, only visible to JavaScript.

    shortcoming

    • Delay - AJAX creates an HTTP request, and HTTP requests travel over the network and have network delays.
    • Status - Data obtained through a separate HTTP request will not contain any information obtained from the HTTP request to obtain the HTML document. You might need this information (for example, if the HTML document was generated in response to a form submission), and if you do, you'll have to transmit it somehow. If you have excluded embedding data into the page (which you have excluded if you use this technique), then you can only use cookies/sessions, which may be subject to race conditions.

    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

    /* 在这里执行一些操作,比如与数据库、文件会话等进行交互
     * 超越世界,无间地带,闪烁之城和加拿大。
     *
     * AJAX通常使用字符串,但你也可以输出JSON、HTML和XML。
     * 这完全取决于你发送的AJAX请求的Content-type头。 */
    
    echo json_encode(42); // 最后,你需要`echo`结果。
                          // 所有数据都应该使用`json_encode`。
    
                          // 你可以在PHP中`json_encode`任何值,数组、字符串,
                          // 甚至对象。
    

    index.php (or the name of the actual page)

    <!-- 省略 -->
    <script>
        fetch("get-data.php")
            .then((response) => {
                if(!response.ok){ // 在解析(即解码)JSON数据之前,
                                  // 检查是否有任何错误。
                    // 如果有错误,抛出错误。
                    throw new Error("Something went wrong!");
                }
    
                return response.json(); // 解析JSON数据。
            })
            .then((data) => {
                 // 在这里处理响应。
                 alert(data); // 将弹出:42
            })
            .catch((error) => {
                 // 在这里处理错误。
            });
    </script>
    <!-- 省略 -->
    

    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

    • 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 use some sort of <input type=hidden> to store the information because from inputNode.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 the data-* attribute for JavaScript-related data on specific elements.
    • Clutter the source code - PHP generated data is output directly into the HTML source code, which means you get a larger and less focused HTML source code.
    • Harder to get structured data - Structured data must be valid HTML, otherwise you have to escape and convert the string yourself.
    • Tightly couple PHP with data logic - Because PHP is used for presentation, there is no way to cleanly separate the two.

    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

    <!-- 省略 -->
    <div id="dom-target" style="display: none;">
        <?php
            $output = "42"; // 再次,执行一些操作,获取输出。
            echo htmlspecialchars($output); /* 必须转义,否则结果
                                               将不是有效的HTML。 */
        ?>
    </div>
    <script>
        var div = document.getElementById("dom-target");
        var myData = div.textContent;
    </script>
    <!-- 省略 -->
    

    3. Echo data directly into JavaScript

    This is probably the easiest way to understand.

    advantage

    • Very easy to implement - The cost to achieve this is very low and easy to understand.
    • Does not pollute source code - Variables are output directly into JavaScript, so

      reply
      0
  • Cancelreply