How can a button click add values to an array in PHP without redirecting to another page?

To add values to an array in PHP without redirecting to another page when a button is clicked, you can use AJAX to send a request to a PHP script that will handle the addition of the values to the array. This allows you to update the array without refreshing the page.

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['value'])) {
    session_start();
    $value = $_POST['value'];
    
    if (!isset($_SESSION['array'])) {
        $_SESSION['array'] = [];
    }
    
    array_push($_SESSION['array'], $value);
    
    echo json_encode(['success' => true]);
    exit;
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Add Value to Array</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
    <button id="addValue">Add Value</button>

    <script>
        $(document).ready(function() {
            $('#addValue').click(function() {
                var value = 'new value'; // Change this to the value you want to add
                $.ajax({
                    type: 'POST',
                    url: 'add_value.php',
                    data: { value: value },
                    success: function(response) {
                        if (response.success) {
                            console.log('Value added to array successfully');
                        } else {
                            console.log('Failed to add value to array');
                        }
                    }
                });
            });
        });
    </script>
</body>
</html>