Wednesday, May 20

Passing Values From JavaScript to PHP and Back

1. PHP to JavaScript

    <?php
        echo "Just wanted to say $hello";
    ?>

2. JavaScript to PHP

    <script>
        function sayHelloWorld() {
            var hello = "hello";
            var world = "world";
       
            window.location.href = "somepage.php?w1=" + hello + "&w2=" + world;
        }
    </script>
   
3. PHP Receiving and Processing The Variables

    <?php
    function sayHiBack() {
       // Check if we have parameters w1 and w2 being passed to the script through the URL
       if (isset($_GET["w1"]) && isset($_GET["w2"])) {
   
          // Put the two words together with a space in the middle to form "hello world"
          $hello = $_GET["w1"] . " " . $_GET["w2"];
   
          // Print out some JavaScript with $hello stuck in there which will put "hello world" into the javascript.
          echo "<script language='text/javascript'>function sayHiFromPHP() { alert('Just wanted to say $hello!'); }</script>";
       }
    }
    ?>

No comments:

Post a Comment