JavaScript variables passed into new variable object POSTing as undefined to another page

Viewed 48

I have a page called SQLFailover.php that shows a table with two rows. Each row will have a toggle button. The toggle button on the first row will be set to primary and the server name on that row will be determined by a SQL query done earlier in the code. The second row’s toggle will be set to secondary and will get the server name from the same SQL query. When either button is toggled, I need the button to trigger a post to SQLAction.php. That page will call a powershell script that will update server names in a table then be redirected back to SQLFailover.php by using a header() cmd. When the SQLFailover.php is reloaded, the section with the comment “get current primary server and secondary server from SQL Table” will do a query which retrieves the primary and secondary servers to display, which at this point, will have been changed from the powershell that will be added to the SQLAction.php page at a later time. The trouble I am having is that when my current script POSTs to the action page the key => value pairs are undefined. Please help me to understand how this is happening and correct my code. Thank you.

SQLFailover.php

<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
 <div class="portlet-body">
        <div class="table-scrollable">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th class="all"> Location </th>
                        <th class="all"> Status </th>
                    </tr>
            </thead>
            <tbody>
                <?php $UserSession = $_SESSION['jigowatt']['username'];?>
                <script> var UserSession = '<?=$UserSession?>';</script>
                <?php
                $env = "CERT";
                if (isset($env)) {
                    if ($env === 'CERT') {
                        
                        $stageEnvironmentType = "CERT";
                        $SQLFileName = "AGL_C_ 01\C01,10995";
                        $serverName = $SQLFileName; 
                    
                        }elseif($env === 'PROD') {
                        
                        $stageEnvironmentType = "PROD";
                        $SQLFileName = "AGL_P_ 01\P01,11111";
                        $serverName = $SQLFileName; 

                    }

                    //SQLServer Connection
                    $connectionInfo = array( "Database"=>"master");
                    $conn = sqlsrv_connect( $serverName, $connectionInfo );

                    if( $conn === false ) {
                        die( print_r( sqlsrv_errors(), true));
                    }else{
    //get current primary server and secondary server from SQL Table
                        $sql = file_get_contents('SQLSelect.sql');
                        $stmt = sqlsrv_query( $conn, $sql);

                        if( $stmt === false ) {
                            die( print_r( sqlsrv_errors(), true));
                        }

                        while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
                            $conn_current_PrimaryReplica = $row['conn_current_PrimaryReplica'];
                            $conn_new_PrimaryReplica = $row['conn_new_PrimaryReplica'];
                            ?>
                            <tr>
                                <td> <?php echo $conn_current_PrimaryReplica;?> </td>
                                <td> 
                                    <input data-server-name="<?php echo "$conn_new_PrimaryReplica";?>" class="toggle-event" checked type="checkbox" data-toggle="toggle" data-on="Primary" data-onstyle="success" data-off="Secondary" data-offstyle="danger" data-size="small" />
                                </td>
                            </tr>
                            <tr>
                                <td> <?php echo $conn_new_PrimaryReplica; ?> </td>
                                <td>
                                    <input data-server-name="<?php echo "$conn_current_PrimaryReplica";?>" class="toggle-event" type="checkbox" data-toggle="toggle" data-on="Primary" data-onstyle="success" data-off="Secondary" data-offstyle="danger" data-size="small" />    
                                </td>
                            </tr>
                            <?php
                      }
                      
                      sqlsrv_free_stmt($stmt);
                       
                    }
                }
                ?>
            </tbody>
        </table>
    </div>
</div>

<script>
     $(function() {
        $('.toggle-event').change(function() {
            var serverName = $(this).data('server-name');
            var mode = $(this).prop('checked');
            var username = '<?=$UserSession?>';
        
            var payload = {
              server: serverName,
              username: username
            };
            var form = document.createElement('form');
            form.style.visibility = 'hidden'; 
            form.method = 'POST'; 
            form.action = '/SQLAction.php';
            for (key in Object.keys(payload)) {
            var input = document.createElement('input');
            input.name = key;
            input.value = payload[key];
            form.appendChild(input); 
            }
            document.body.appendChild(form);
            form.submit(); 
          })
    })
</script>

Below is the SQLAction.php page.

<?php
echo "<b>begin POST values</b><br><br>";
foreach ($_POST as $key => $value) {
echo "<tr>";
    echo "<td>";
    echo $key;
    echo "</td>";
    echo " : ";
    echo "<td>";
    echo $value;
    echo "</td>";
    echo "</tr>";
    echo "<br>";
}
echo "<b>end of POST values</b><br><br>";

header('refresh:5; / SQLFailover.php ');
?>
2 Answers

The object key iteration of your code seems not correct (at least it appears to be non-standard) and the values extracted are found to be undefined. (I have tested your code and it generates undefined values)

Please iteration your Object keys thru the Object.keys(obj).forEach construct, with the following syntax:

Object.keys(obj).forEach(key => {
//  console.log(key, obj[key]);
});

Hence, for your case , please change the block

 for (key in Object.keys(payload)) {
            var input = document.createElement('input');
            input.name = key;
            input.value = payload[key];
            form.appendChild(input); 
            }

to

Object.keys(payload).forEach(key => {

            var input = document.createElement('input');
            input.name = key;
            input.value = payload[key];
            form.appendChild(input); 
});

The page is now working with a change to the for line in the function.

<script>
$(function() {
    $('.toggle-event').change(function() {
        var serverName = $(this).data('server-name');
        var mode = $(this).prop('checked');
        var username = '<?=$UserSession?>';
        
        var payload = {
            server: serverName,
            mode: mode,
            username: username
        };
        var form = document.createElement('form');
        form.style.visibility = 'hidden';
        form.method = 'POST';
        form.action = 'SNFailover/SQLAction.php';
        $.each(Object.keys(payload), function(index, key) {
        var input = document.createElement('input');
            input.name = key;
            input.value = payload[key];
            form.appendChild(input)
        });
        document.body.appendChild(form);
        form.submit();
    });
})
Related