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 the Server-side scripting for doing it.

In PHP, you can simply use 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 a some <img> element 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 underscore (‘_’). The same number is used in <span > 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 id='delete_1'>Delete</span>
 </div>

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

 <div class='content'>
  <img src='images/image2.jpg' id='img_3' width='100' height='100'>
  <span id='delete_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 a new removefile.php file.

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

Check if a file exists. If exists then pass $path in unlink() function to remove file.

Return $return_text.

Completed Code

<?php

$path = $_POST['path'];

$return_text = 0;

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

  // Remove file 
  unlink($path);

  // Set status
  $return_text = 1;
}else{

  // Set status
  $return_text = 0;
}

// Return status
echo $return_text;

5. jQuery

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

Select image source on the base of <span> element and sending its source in AJAX request.

If the AJAX callback successfully and response equals to 1 then replacing the <img> source with noimage.png.

Completed Code

$(document).ready(function(){

  // Delete
  $('.content span').click(function(){
    var id = this.id;
    var split_id = id.split("_");

    // Selecting image source
    var imgElement_src = $( '#img_'+split_id[1] ).attr("src");
 
    // AJAX request
    $.ajax({
      url: 'removefile.php',
      type: 'post',
      data: {path: imgElement_src},
      success: function(response){
 
        // Changing image source when remove
        if(response == 1){
          $("#img_" + split_id[1]).attr("src","images/noimage.png");
        }
      }
    });
  });
});

6. Demo

Click on the Delete button to see the changes.


7. Conclusion

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

In this tutorial, I performed 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.

Related Post

Spread the love
  •  
  •  
  •  
  •  
  •  
  •  

4 Comments

  1. subbu said:

    thanks, this script is very helpfull.

    January 24, 2018
    Reply
  2. Sandro Toni said:

    Hi, very good script.

    The only thing is that it doesnt delete the thumbnail file.

    How to make it possible?

    Thanks.
    Sandro Toni

    February 17, 2019
    Reply

Leave a Reply

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