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

Technology CommunityCategory: PHPHow do I pass variables and data from PHP to JavaScript?
VietMX Staff asked 4 years ago

There are actually several approaches to do this:

  • Use AJAX to get the data you need from the server.
    Consider get-data.php:
echo json_encode(42);

Consider index.html:

<script>
    function reqListener () {
      console.log(this.responseText);
    }

    var oReq = new XMLHttpRequest(); // New request object
    oReq.onload = function() {
        // This is where you handle what to do with the response.
        // The actual data is found on this.responseText
        alert(this.responseText); // Will alert: 42
    };
    oReq.open("get", "get-data.php", true);
    //                               ^ Don't block the rest of the execution.
    //                                 Don't wait until the request finishes to
    //                                 continue.
    oReq.send();
</script>
  • Echo the data into the page somewhere, and use JavaScript to get the information from the DOM.
<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>
  • Echo the data directly to JavaScript.
<script>
    var data = <?php echo json_encode("42", JSON_HEX_TAG); ?>; // Don't forget the extra semicolon!
</script>