Search code examples
phpjavascriptjqueryunlink

PHP jquery ajax unlink images from folder not working


I am trying to show and delete images that are stored in folders, but I can not run the JS code that removes each.

My code php in the index.php:

// folder with files    
$pathimages = $_SERVER['DOCUMENT_ROOT'];
$pathimages .= "/uploads/files/";

// showing images
foreach(glob($pathimages.'*') as $filename){
    $ext = pathinfo($filename, PATHINFO_EXTENSION);
    $name_only = basename($filename, ".".$ext);

    echo "<img src=\"../uploads/files/" .$name_only.".".$ext. "\" width=\"30\" />
        <a onclick=\"DeleteImage(".$name_only.",".$ext."); return false;\" href=\"javascript:;\">X</a>
        <br />";
}

(Im sending the file-name and extension in two vars, I dont know why)

When I click on the "X", call the function "DeleteImage", but doesnt work.

JS function from .js file imported:

 function DeleteImage(name_only, ext){
    var parametros = {
        "name_only" : name_only,
        "ext" : ext
    };

    $.ajax({
        url: 'views/delete_image.php',
        type: "POST",
        data: parametros,
        success: function(datos){
            console.log("check");
        }
    });
}

And the delete file php:

$name_only = $_POST['name_only'];
$ext = $_POST['ext'];

$pathimages = $_SERVER['DOCUMENT_ROOT'];
$pathimages .= "/uploads/files/";

unlink($pathimages . $name_only .".". $ext);
echo "Deleted";

I have something similar but with records in the database and works OK, using GET method, deleting, editing, etc. But here the problems started. Thank you very much and I apologize for my english.


Solution

  • I think the problem is with the array you are passing,

    Try using,

    data:{name_only:name_only,ext:ext},
    

    to pass the parameters or you may consider passing them as json arrays.