简体   繁体   中英

jQuery $.ajax and php to delete a file

I'm trying to delete a file with jQuery's $.ajax and php. I have the following.

/js/whatever.js

$('.deleteimage').live('click', function() {
    $imagefile = 'http://domain.com/images/1/whatever.jpg';
    $imagethumb = 'http://domain.com/images/1/thumbnail/whatever.jpg';
    $.ajax({
        type: 'POST',
        data: {
            action: 'deleteimage',
            imagefile: $imagefile,
            imagethumb: $imagethumb,
        },
        url: 'script.php',
        success: function(msg) {
            alert(msg);
        }
    })
})

/php/script.php

<?php
    if($_GET["action"]=="deleteimage")
    {
        $imagefile = $_REQUEST['imagefile'];
        $imagethumb = $_REQUEST['imagethumb'];
        $imagefileend = '../images'.end(explode('images',$imagefile)); //This will get me the path to the image ../images/1/whatever.jpg without the domain which is the correct path to the file. I tried that path directly and it deleted the file. 
        $imagethumbend = '../images'.end(explode('images',$imagethumb));

        unlink($imagefileend);
        unlink($imagethumbend);
    }
?>

All path are correct. In firebug i see the post variables are being sent correctly to script.php, however files are not being deleted. What am i doing wrong.

In jQuery you use POST but in PHP you use GET. Change to if($_POST["action"]=="deleteimage") and please don't use $_REQUEST but $_POST

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM