Wednesday, May 20

Post Multiple JavaScript Values to PHP Using jQuery AJAX

Step 1. To Package Up data for Sending

    <script>
        // Create an object using an object literal.
        var ourObj = {};
       
        // Create a string member called "data" and give it a string.
        // Also create an array of simple object literals for our object.
        ourObj.data = "Some Data Points";
        ourObj.arPoints = [{'x':1, 'y': 2},{'x': 2.3, 'y': 3.3},{'x': -1, 'y': -4}];

    </script>
   
Step 2: Transmitting This Data in jQuery AJAX

    <script>
        $.ajax({
           url: 'process-data.php',
           type: 'post',
           data: {"points" : JSON.stringify(ourObj)},
           success: function(data) {
                // Do something with data that came back.
           }
        });
    </script>
   
Step 3: Package Sent, Package Received

    <?php
    // Test if our data came through
    if (isset($_POST["points"])) {
        // Decode our JSON into PHP objects we can use
        $points = json_decode($_POST["points"]);
   
        // Access our object's data and array values.
        echo "Data is: " . $points->data . "<br>";
        echo "Point 1: " . $points->arPoints[0]->x . ", " . $points->arPoints[0]->y;
    }
    ?>

No comments:

Post a Comment