JQUERYIntermediate

Add Delete Image via jQuery AJAX

PB Pb28 Master Team July 12th, 2022 Intermediate

📦 Get the complete source code for this tutorial

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.

javascript
$("#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,

javascript
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

📦 Download the full project files and try it locally