Petru Lebada
Petru Lebada

Reputation: 1682

Delete a file with ajax request

I'm trying to delete a file with ajax request:

javascript:

function deleteFile(file_path)
{
    var r = confirm("Sure?")
    if(r == true)
    {
        $.ajax({
          url: 'delete_file.php',
          data: {'file' : file_path },
          method: 'GET',
          success: function (response) {
             alert('Deleted!');

          },
          error: function () {
             alert('Not Deleted!');

          }
        });
    }
}

delete_file.php :

unlink($_GET['file']);

It returns true on succes,but the file is not deleted.

Upvotes: 4

Views: 9051

Answers (2)

jogesh_pi
jogesh_pi

Reputation: 9782

Check the response in AJAX, Best is use JSON DATA to check the response:

// Default AJAX request type is GET so no need to define  
$.ajax({
      url: 'delete_file.php',
      data: {'file' : file_path },
      dataType: 'json', 
      success: function (response) {
         if( response.status === true ) {
             alert('File Deleted!');
         }
         else alert('Something Went Wrong!');
      }
    });

Do It like this in PHP:

// First Check if file exists
$response = array('status'=>false);

if( file_exists('FILE_PATH/FILENAME') ) {
    unlink('FILE_PATH/FILENAME');
    $response['status'] = true;
}

// Send JSON Data to AJAX Request
echo json_encode($response);

Make sure you are giving the complete path with filename to unlink() function

Upvotes: 5

Veerendra
Veerendra

Reputation: 2622

Try this you need to check file, give permission, then delete it

$filename = 'full absolute file path';
if(file_exists($filename)) {
    @chmod($filename, 0777);
    @unlink($filename);
    return true;
}

As there can be two issues either the file path is not correct or the file is not having permission.

With the above code both will be checked.

Upvotes: 1

Related Questions