Help me find a bug. The construction does not work.

Js:

function delete() { var msg = $('#closed').serialize(); $.ajax({ type: 'POST', url: 'submit.php?delete=<? $filename ?>', data: msg, success: function(data) { alert("Файл удален"); }, error: function(xhr, str){ alert('Возникла ошибка: ' + xhr.responseCode); } }); 

Php:

 $dir = 'downloads'; $files = scan_dir($dir); if($files == false) printf("Каталог пуст"); else { printf("<table class='bordered'> <thead> <tr> <th>Название файла</th> <th>Размер</th> <th>Удалить</th> </tr> </thead>"); } foreach($files AS $i => $filename) { printf( '<tr><td><a download href="/downloads/%s" style="color:black">%s</a> </td><td style="white-space:nowrap;">%s</td><td><form action="javascript:void(null);" id="closed" method="post"><button onclick="delete()">del</a></form></td></tr>', urlencode( $filename), $filename, human_filesize(filesize( $dir . '/' . $filename)), urlencode( $filename), $filename ); } 

submit.php:

 if (isset($_GET['delete'])) { unlink("./downloads/".$_GET['delete']); } 

Ideally, the file should be deleted, the link to which the user clicked, without reloading the table itself.

  • In fact, it turns out that you always delete the same file. the file name as the delete() parameter is not passed .... - cyadvert
  • specify the absolute path to the file in unlink() - mix

1 answer 1

Change $_GET to $_POST

 if (isset($_GET['delete'])) { unlink("./downloads/".$_POST['delete']); } 

And also pass the file name as the delete() parameter

 printf( '<tr><td><a download href="/downloads/%s" style="color:black">%s</a> </td><td style="white-space:nowrap;">%s</td><td><form action="javascript:void(null);" id="closed" method="post"><button onclick="delete(%s)">del</a></form></td></tr>', urlencode( $filename), $filename, human_filesize(filesize( $dir . '/' . $filename)), urlencode( $filename), $filename ); 

And the JS function slightly change:

 function delete(filename) { var msg = $('#closed').serialize(); $.ajax({ type: 'POST', url: 'submit.php?delete=' + filename, 
  • No, also does not work - Rasrow