Images can be added or deleted using jQuery and PHP script via AJAX. In a previous tutorial, we have seen examples like PHP AJAX image upload and multiple image upload. But in those examples, we didn’t have a delete option.
In image add, we call PHP file upload script to upload the chosen image into a target folder. While deleting, we call PHP to remove the image file from the folder. We use PHP unlink() to remove the file by specifying a target path.
This jQuery script is for invoking PHP file upload script for adding files to a target. On successful image file upload, this script will show the image to the browser.
This image element is constructed in PHP and returned as an AJAX response.
$("#uploadForm").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$("#targetLayer").html(data);
},
error: function(){}
});
}));
This jQuery script is containing AJAX method to call PHP Image delete code. In PHP we use in-built unlink() method to delete the image with the reference of its path. Once the file is deleted, then the image element is replaced by a no-image text. The code is,
function deleteImage(path) {
$.ajax({
url: "delete.php",
type: "POST",
data: {'path':path},
success: function(data){
$("#targetLayer").html('<div class="no-image">No Image</div>');
},
error: function(){}
});
}