Ajax call delete cakephp

1.5k Views Asked by At

I'm trying to use ajax delete to delete records that, when clicked, confirms before sending the request. the record is deleted and it work but the problem is after deleting nothing change in the view until after I reload the page manually. I want to show the result in view just after click "ok" in the dialog

my ajax code :

$(document).ready(function() { 
  if($('.confirm_delete').length) {
       $('.confirm_delete').click(function(){
         var result = confirm('Are you sure you want to delete this?');
         $('#flashMessage').fadeOut();
         if(result) {
           $.ajax({
              type:"POST",
              url:$(this).attr('href'),
              data:"ajax=1",
              dataType: "json",
              success:function(response){
                }
          });
      }

      return false;
    });
  }
});

in view :

echo $this->Js->link('Delete', array('controller' => 'publications', 'action'=>'delete', $publication['Publication']['id']),
  array('escape' => false, 'class'=>'confirm_delete'));
2

There are 2 best solutions below

4
On

This is not a CakePHP problem but a JS problem only. If yor delete callback was successful without any error returned you have to remove the related content from the DOM tree. Using jquery this can be done by calling remove() on any selector you want to remove.

0
On
$(document).ready(function(){
if($('.confirm_delete').length) {
   $id=$(this).attr('id');

   $('.confirm_delete').click(function(){
   var result = confirm('Are you sure you want to delete this?');
    $('#flashMessage').fadeOut();

    if(result) {
        $.ajax({
            type:"POST",
            url:$(this).attr('href'),
            data:"ajax=1",
            dataType: "json",
            success:function(response){

                }
        });


        $('#row'+$id).remove();

}


return false;
});

} });

For some reason the $(this).attr('id') does not work ... how to get id of the element selected to remove it I have on my view :

<div class="box_detail" id="row<?php echo $publication['Publication']['id']; ?>">