John Davidson

php - JavaScript Fetch() Not Differentiating Between The Update And Delete Functionality Of A Form

0 comments
Message:


I have a form that is currently processed on the server with PHP/MySQL that uses the JavaScript fetch() API in the frontend so that when details are submitted to the database the page doesn't reload on form submission.


The form(s) themselves are within a loop that outputs multiple instances of the form onto the page.


For the JavaScript to work it relies on the following PHP (I will show more detailed code at the end of the question)


if($_SERVER['REQUEST_METHOD'] == 'POST') {
// PHP to process form details
}

The javascript is:


var forms = document.querySelectorAll('form');

forms.forEach(item => {

item.addEventListener("submit", function (evt) {

evt.preventDefault();

const formData = new FormData(this);

fetch("upload-details.php", {
method: 'post',
body: formData
}).then(function(response){
return response.text();
}).catch(function (error){
console.error(error);
})

// remove item after form details submitted
item.remove();

})

})

I now wish to add a delete button that also works with the JS fetch API. The problem I have is, I can't get the JS Fetch to differentiate between when the form details are updated and when the record should be deleted?


I've tried changing this:


if($_SERVER['REQUEST_METHOD'] == 'POST') {
// PHP to process form details (both update and delete)
}

To this (to no avail):


if(isset($_POST['update'])) {
// PHP to process form details
}

if(isset($_POST['delete'])) {
// PHP to process form details
}

When I turn off the JS fetch() API code, the code below behaves exactly as expected from the PHP / MySQL point of view (i.e. it updates and deletes the records accordingly).


MORE DETAILED CODE:


<?php
isset($_REQUEST['username']) ? $username = $_REQUEST['username'] : header("Location: login.php");

// the following variable is already fetched with PHP from the database
// it is added as a value to a hidden input element in the HTML form shown below
$db_image_id = htmlspecialchars($row['image_id']);

if($_SERVER['REQUEST_METHOD'] == 'POST') {

$image_title = $_POST['image-title'];
$image_tags = $_POST['image-tags'];
$image_id = $_POST['image-id']; // value attribute from hidden form element

if(empty(trim($image_title))){
$error[] = "Image Title cannot be blank";
}

if (!isset($error)) {

try {

$sql = "UPDATE imageposts SET
image_title = :image_title,
image_tags = :image_tags

WHERE image_id = :image_id";

$stmt = $connection->prepare($sql);

$stmt->execute([
':image_title' => $image_title,
':image_tags' => $image_tags,
':image_id' => $image_id
]);

} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}

} else {
// give values an empty string to avoid an error being thrown before form submission if empty
$image_title = $image_tags = "";
}

}

//---- DELETE DETAILS
if(isset($_POST['upload-details-delete'])) {

$image_id = $_POST['image-id']; // 'value' attribute from hidden form element

try {

$sql = "DELETE FROM `lj_imageposts` WHERE image_id = :id";

$stmt = $connection->prepare($sql);

$stmt->execute([
':id' => $image_id
]);

} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}

}

// data is fetched with PHP to add to the form
//(I haven't included this code because there is a lot of values outputted onto the form, and when the JavaScript fetch() is turned off it all works OK)
while ($row = $stmt->fetch()) {

?>

<!-- form that holds the update and delete elements -->
<div class="upload-details-component">
<form method="post" enctype="multipart/form-data">
<button name="delete">Delete</button>
<div class="upload-details-image-wrapper">
<!-- ** image is outputted here from database ** -->
</div>
<div class="edit-zone">
<div class="form-row">
<label>Image Title</label>
<input type="text" name="image-title" placeholder="Image Title" >
</div>
<div class="form-row">
<label>Image Tags</label>
<textarea type="text" name="image-tags"></textarea>
</div>
<div class="form-row">
<input type="submit" name="upload" value="COMPLETE UPLOAD">
</div>
</div>
<input type="hidden" name="image-id" value="<?php echo $db_image_id?>">
</form>
</div>

<?php } ?>


My Answer:
To differentiate between the update and delete functionality in your PHP code, you can add a hidden input field in your form that specifies the action being taken (update or delete). Then, in your PHP code, you can check the value of this hidden input field to determine which action to perform.

Here's how you can modify your form and PHP code:

1. Update your form to include a hidden input field for the action:
html


For the delete button, you can change the value of the hidden input field to "delete":
html




2. Modify your PHP code to check the value of the "action" field:
php
if($_SERVER['REQUEST_METHOD'] == 'POST') {

$action = $_POST['action'];

if($action == 'update') {
// PHP to process form details for update
} elseif($action == 'delete') {
// PHP to process form details for delete
}

}


By checking the value of the "action" field in your PHP code, you can differentiate between the update and delete functionality of your form. This way, the JavaScript fetch() API will send the correct action to the server, and your PHP code will handle it accordingly.

Rate this post

5 of 5 based on 8046 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us