XHR Data Transfer Between Javascript and PHP

  1. JS dispatch was successful. But it does not enter the if block in PHP. Whereas before I restarted the computer successfully entered the if block in PHP.

  2. When successful, the data received is “1”. Even though I have set the static data sent is “4”.

Javascript code:

                let xhr = new XMLHttpRequest();
                let dataStorage = new FormData();
                dataStorage.append('dataStorage', 4);

                console.log("Data yang dikirim:", dataStorage.get('dataStorage'));

                xhr.open('POST', 'sistemDB.php', true);
                xhr.onload = function() {
                    if (xhr.status === 200) {
                        console.log("AJAX request completed with status: " + xhr.status);
                        // console.log(xhr.responseText);
                    } else {
                        console.log("AJAX request failed with status: " + xhr.status);
                    }
                };
                xhr.onerror = function() {
                    console.log("Request failed");
                };
                xhr.send(dataStorage);
                console.log("Send berhasil");

PHP code:

                                <?php
                                if ($_SERVER["REQUEST_METHOD"] == "POST") {
                                    echo '<pre>';
                                    var_dump($_POST); // Display all POST data
                                    echo '</pre>';

                                    // Alternative way to check raw POST data
                                    echo '<pre>';
                                    echo 'Raw POST data: ' . file_get_contents('php://input');
                                    echo '</pre>';

                                    if (isset($_POST['dataStorage'])) {
                                        $data = $_POST['dataStorage'];
                                        echo htmlspecialchars($data); // Use htmlspecialchars to prevent XSS attacks
                                    } else {
                                        echo 'dataStorage not set';
                                    }
}
?>

Please help me

I am trying to change the static value to send to PHP, to a value of “4”

Notes: php and javascript scripts are located in the same file “systemDB.php”.