AJAX Delete and Update Operations with PHP
Updating and deleting records are state-changing operations. The browser can provide a convenient interface, but every permission and validation check must run on the server.
Send an update
const response = await fetch('/api/item-update.php', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id: 42, name: 'Updated item' })
});
if (!response.ok) throw new Error('Update failed');
Use prepared statements
$stmt = $pdo->prepare('UPDATE items SET name = :name WHERE id = :id');
$stmt->execute(['name' => $name, 'id' => $id]);
Validate the identifier and field constraints before executing the query. Check authorization for the specific record, not only for the general page.
Deletion safeguards
Ask for confirmation when deletion is destructive, handle already-deleted records gracefully, and consider soft deletion or an undo workflow where appropriate. Protect requests with CSRF tokens and log important administrative actions without storing unnecessary personal data.