Search code examples
phpjquerycakephpajax-upload

How can I delete files with CakePHP and Ajax?


I'm in a page called 'add.cpt' that has a list of images. The user has the option to remove the images but I can't make it work. In the event of click I try to call an ajax trying to pass the name of the image and id of the item (.../item/imageName) but it does delete the image and alerts what seems to be the content of delete_photo_file.ctp. It looks like the ajax is using the URL but it is not sending the data to delete the file wanted.

ItemsController:

App::uses('File', 'Utility');
class ItemsController extends AppController{

[...]

public function deletePhotoFile(){
  //$this->autoRender = false; //did not tested but maybe I need to use this
  $imgName = //don't know how to get it from ajax call
  $itemId = //don't know how to get it from ajax call
  $file = new File($dir.'/'.$itemId.'/'.$imgName);
  $file->delete();
} 

}

Ajax Call (from my ctp file):

$('#delete').click(function (){
[...]

var itemId=$('#itemId').val(); //comes from hidden input
var imgName = $('#imgName').val(); //comes from hidden input

$.ajax({
  type: 'POST',
  url:'http://localhost/html/Project/v5/CakeStrap/items/deletePhotoFile/',
  data:{"itemId":itemId, imgName: imgName},
  success: function(data){
    alert(data); //alerts some HTML... seems to be delete_photo_file.ctp content
  }
});

});

Can anyone help me? Thanks!


Solution

  • In your ItemsController, make sure you actually load the File utility class, by adding:

    App::uses('File', 'Utility');
    

    Just below the opening <?php tag before your class definition. In your action you can just use $this->request->data to get the data keys. Also, return the action of the delete() function, so you can trigger your AJAX success/error call accordingly.

    public function deletePhotoFile() {
        $imgName = $this->request->data['imgName'];
        $itemId = $this->request->data['itemId'];
        /**
         * Where is the $dir below actually set? Make sure to pass it properly!
         * Furthermore, it's always cleaner to use DS constant
         * (short for DIRECTORY_SEPARATOR), so the code will work on any OS
         */
        $file = new File($dir . DS . $itemId . DS . $imgName);
        return $file->delete();
    } 
    

    Finally, mind your quotes in the AJAX call:

    data:{"itemId":itemId, imgName: imgName},
    

    Should become:

    data:{"itemId":itemId, "imgName": imgName},
    

    As otherwise, you just call the imgName JS var twice.