javascriptphp

How do I pass variables and data from PHP to JavaScript?


I have a variable in PHP, and I need its value in my JavaScript code. How can I get my variable from PHP to JavaScript?

I have code that looks like this:

<?php
$val = $myService->getValue(); // Makes an API and database call

On the same page, I have JavaScript code that needs the value of the $val variable to be passed as a parameter:

<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>

Solution

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

    In no particular order:

    1. Use AJAX to get the data you need from the server.
    2. Echo the data into the page somewhere, and use JavaScript to get the information from the DOM.
    3. Echo the data directly to JavaScript.

    In this post, we'll examine each of the above methods, and see the pros and cons of each, as well as 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.

    Pros

    Cons

    Implementation Example

    With AJAX, you need two pages, one is where PHP generates the output, and the second is 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 named like)

    <!-- 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 above combination of the two files will alert 42 when the file finishes loading.

    Some more reading material

    2. Echo the data into the page somewhere, and use JavaScript to get the information from the DOM

    This method is less preferable to AJAX, but it still has its advantages. It's still relatively separated between PHP and JavaScript in a sense that there is no PHP directly in the JavaScript.

    Pros

    Cons

    Implementation Example

    With this, the idea is to create some sort of element which will not be 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 the data directly to JavaScript

    This is probably the easiest to understand.

    Pros

    Cons

    Implementation Example

    Implementation is relatively straightforward:

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

    Good luck!