How to delete file with jQuery AJAX

Using Client-side scripts like – jQuery and JavaScript it is not possible to delete any files. Need to use Server-side scripting for doing it.

In PHP, you can simply use the unlink() function this removes a file from your server if it exists.

Sometimes you have the requirement to delete a resource file without reloading the page.

This cannot totally be done with PHP you need to use jQuery or JavaScript with it by which send AJAX request to your server for removing a file and according to the response make changes on your Client-side.

For demonstration purpose, I create some <img> elements with Delete Button. When the Button gets clicked then remove the file using jQuery AJAX and replace the <img> source with the default image.

How to delete file with jQuery AJAX


Contents

  1. unlink()
  2. HTML
  3. CSS
  4. PHP
  5. jQuery
  6. Demo
  7. Conclusion

The unlink() function deletes a file from the server. It returns TRUE when file successfully deleted otherwise returns FALSE.

Syntax –

unlink( file path );

You only need to pass the file path which you want to remove.

Now you know how to remove a file using PHP. So let’s implement this with jQuery AJAX.


2. HTML

Created 3 <img > elements and for deleting the image file created <span > elements.

In <img > element specify id attribute where contains a number separating with an underscore (‘_’). The same number is used in <span > data-id attribute.

Use it select image element when <span > get clicked with jQuery.

Completed Code

<div class='container'>
 <div class='content'>
  <img src='images/image1.jpg' id='img_1' width='100' height='100'>
  <span data-id='1'>Delete</span>
 </div>

 <div class='content'>
  <img src='images/image2.jpg' id='img_2' width='100' height='100'>
  <span data-id='2'>Delete</span>
 </div>

 <div class='content'>
  <img src='images/image2.jpg' id='img_3' width='100' height='100'>
  <span data-id='3'>Delete</span>
 </div>

</div>

3. CSS

.container{
  margin: 0 auto;
}

.content{
  width: 100px;
  float: left;
  margin-right: 5px;
  border: 1px solid gray;
  border-radius: 3px;
  padding: 5px;
}

/* Delete */
.content span{
  border: 2px solid red;
  display: inline-block;
  width: 99%; 
  text-align: center;
  color: red;
}
.content span:hover{
  cursor: pointer;
}

4. PHP

Create ajaxfile.php file.

Read $_POST['path'] and assign to $path.

Check if a file exists. If exists then pass $path to unlink() function to remove the file and return 1.

If the file does not exist then return 0.

Completed Code

<?php

if(isset($_POST['path'])){
   $path = $_POST['path']; 

   // Check file exist or not 
   if( file_exists($path) ){ 
      // Remove file 
      unlink($path); 

      // Set status 
      echo 1; 
   }else{ 
      // Set status 
      echo 0; 
   } 
   die;
}

die;

5. jQuery

Performing Delete operation when <span> element clicked inside class='content'.

Read data attribute id value and assign to id variable and use it to select img element src attribute.

Send AJAX POST request to 'ajaxfile.php' and pass {path: imgElement_src} as data.

On AJAX successful callback if response == 1 then replace the <img> source with images/noimage.png.

Completed Code

$(document).ready(function(){

  // Delete
  $('.content span').click(function(){
    var id = $(this).data('id');
 
    // Selecting image source
    var imgElement_src = $( '#img_'+id ).attr("src");
 
    // AJAX request
    $.ajax({
      url: 'ajaxfile.php',
      type: 'post',
      data: {path: imgElement_src},
      success: function(response){
 
        // Changing image source when remove
        if(response == 1){
          $("#img_" + id).attr("src","images/noimage.png");
        }
      }
    });
  });
});

6. Demo

View Demo


7. Conclusion

You can use jQuery AJAX for removing the file, in this way you don’t have the need to reload your whole page. This improves your website user experience.

In this tutorial, I performed a delete operation on the image files you can also do this with any other file like pdf, mp3, video, text file, etc.

Note – The unlink() function completely remove the file from your server so make sure before executing the function.

If you found this tutorial helpful then don't forget to share.
Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request.

4 thoughts on “How to delete file with jQuery AJAX”

Leave a Comment