sasori
sasori

Reputation: 5455

deleting files in javascript

is it possible to delete a file(s) inside the directory by just using javascript ?. what I currently have is, an index.php which displays the name of the files in the same directory and and a checkbox to each file name and at the bottom is a delete button. what I want to happen is, delete all the selected checkboxes once the delete button is clicked. I am not using mysql here, just a plain php file that displays the names. can someone show me how to delete the selected files using javascript ?

Upvotes: 0

Views: 5592

Answers (5)

Sarfraz
Sarfraz

Reputation: 382696

You can not delete files with javascript for security reasons. Bad guys can delete files of your stytem :( However, you can do so with the combination of server-side language such as PHP, ASP.NET, etc using what is know as Ajax.

Note: Javascript is moving to adding/becoming the server-side language options. Node JS is an example of that.

Update Based On Comment:

You can delete files something like this:

<a href="#" class="delete">Delete</a>

JQuery:

$(function(){
    $('a.delete').click(function(){
      $.ajax({
       url:'delete.php',
       data:'id/name here',
       method:'GET',
       success:function(response){
        if (response === 'deleted')
        {
           alert('Deleted !!');
        }
       }
      });
    });
});

PHP:

   if (isset($_GET['id/name here']))
   {
     if (unlink('your_folder_path' . $_GET['id/name here']))
     {
       echo 'Deleted';
     }
   }

Upvotes: 4

user132748
user132748

Reputation:

You need to implement the file deletion function in PHP based on the built-in unlink() function. Be careful here!! for example, you should read the list of file names and calculate an ID for each of them, and your delete function would accept IDs and NOT the real filename(s).

Then, when you send the file list to the browser, it includes the generated IDs as hidden fields or object attributes, etc. From JavaScript, you can use an HTTP request to send a list of file IDs to be deleted, based on the checkboxes. Your PHP script would call your delete function for the IDs.

Upvotes: 1

Karthik
Karthik

Reputation: 3271

In this, use ajax function or otherwise by javascript in onclick function provide the submit action and refresh the whole page.

Upvotes: 0

Aaron Digulla
Aaron Digulla

Reputation: 328594

You don't need JavaScript for that but a HTML form which sends the filenames to a PHP script on the server which deletes the files. See this example.

Upvotes: 0

Jarek
Jarek

Reputation: 5935

You can use AJAX,and delete files using PHP on server. You can't manipulate with files in pure javascript.

Upvotes: 4

Related Questions