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>
Keywords
Related Questions
- What is the best practice for selecting the last record in a database table in PHP?
- How can PDO and prepared statements be utilized in PHP to enhance the security of database queries?
- How can beginners effectively manage includes and autoloads in PHP without getting overwhelmed by manual file inclusions?