How to delete a file from a folder using javascript?

Is there a way to delete files from a folder using javascript ..? Here is my function

function deleteImage(file_name) { var r = confirm("Are you sure you want to delete this Image?") if(r == true) { var file_path = <?php echo dirname(__FILE__) . '/uploads/'?>+file_name; file_path.remove(); } } 
+6
source share
5 answers

You cannot delete anything without the server side of the script ..

In fact, you can use ajax and call the file on the server side to do this, for example.

Make file delete.php

 <?php unlink($_GET['file']); ?> 

and in javascript

 function deleteImage(file_name) { var r = confirm("Are you sure you want to delete this Image?") if(r == true) { $.ajax({ url: 'delete.php', data: {'file' : "<?php echo dirname(__FILE__) . '/uploads/'?>" + file_name }, success: function (response) { // do something }, error: function () { // do something } }); } } 
+13
source

You cannot delete files using javascript for security reasons. However, you can do this with a combination of a server language such as PHP, ASP.NET, etc. using Ajax. The following is an example ajax request that you can add to your code.

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

You cannot do this. In fact, JavaScript is sandboxed and this does not allow such operations.

To delete a file, for this you need a server-side script. It depends on what server language you use to work.

0
source

Javascript is a client-side scripting language. If you want to delete files from the server, use php instead.

0
source

You cannot do this using javascript. But if the file is on the server, you can use php for this. You can use unlink in php.

 unlink($path_to_file); 
0
source

Source: https://habr.com/ru/post/957164/


All Articles