Skip to content

Instantly share code, notes, and snippets.

@taleeb35
Last active August 29, 2015 14:06
Show Gist options
  • Save taleeb35/e61f58af9944511b1669 to your computer and use it in GitHub Desktop.
Save taleeb35/e61f58af9944511b1669 to your computer and use it in GitHub Desktop.
Delete with Jquery
public function delete($id = null) {
if($this->request->is('ajax')) {
//$this->autoRender = false;
if ($this->User->delete($id)) {
$response = $this->Session->setFlash(__('User deleted'));
$response .= $this->redirect(array('action' => 'index'));
} else {
$response = $this->Session->setFlash(__('User was not deleted'));
$response.= $this->redirect(array('action' => 'index'));
}
return json_encode($response);
}
}
$(document).ready(function() {
$('a.delete').click(function(e) {
var __this = this;
e.preventDefault();
var parent = $(this).parent("td").parent("tr");
$.ajax({
type: 'get',
url: $(__this).attr("href"),
beforeSend: function() {
parent.animate({'backgroundColor':'#fb6c6c'},3000);
},
success: function(response) {
if(response.success){
parent.slideUp(300,function() {
parent.remove();
});
}else{
alert("Failed to delete message");
parent.animate({'backgroundColor':'#fff'},1000);//Restore your background back
}
}
});
});
});
@CristianDeluxe
Copy link

    public function delete($id = null) {
        if($this->request->is('ajax')) {
            $this->layout = 'ajax';
            $response = 'Fail';
            if ($this->User->delete($id)) {
                $response= 'OK';
            }
            $this->set('response', $response);
        }
    }

View\YourName\delete.ctp

<?php
echo $response;
?>
$(document).ready(function() {
        $('a.delete').click(function(e) {
            var __this = this;
            e.preventDefault();
            var parent = $(this).parent("td").parent("tr");
                 $.ajax({
                    type: "GET",
                    url: $(__this).attr("href"),
                    cache: false
                })
                .beforeSend: function() {
                    parent.animate({'backgroundColor':'#fb6c6c'},3000);
                }
                .done(function( msg ) {
                    if(msg == "OK"){
                        parent.slideUp(300,function() {
                            parent.remove();
                        });
                    } else {
                        alert("Failed to delete message");
                        parent.animate({'backgroundColor':'#fff'},1000);//Restore your background back
                    }
                });
        });
    });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment