2

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.

3
  • check with if (file_exists($imagefileend)) { unlink($imagefileend); } else{echo "error";} Commented Oct 5, 2011 at 7:25
  • also, you're not echoing anything in php script, so you won't get the msg response in Ajax Commented Oct 5, 2011 at 7:28
  • 2
    I personally would post them all and use $_POST instead of $_GET and $_REQUEST in this condition. Commented Oct 5, 2011 at 7:29

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

4 Comments

GREAT. That was exactly the problem. It's working now using POST. Do you know the reason why it wouldn't work with REQUEST.
This was what I said at the comment. This works because you are sending as POST. Also I suggest avoiding using $_REQUEST in anywhere in your script.
Yes i see why request is not a good idea. Thanks for the link.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.