Add Delete Image via jQuery AJAX

by Vincy. Last modified on July 12th, 2022.

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.

Image Add Script for Uploading Image File

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.

add-delete-image-via-ajax

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(){} 	        
   });
}));

jQuery AJAX Image Delete

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(){} 	        
	});
}

Download

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page