I am trying to delete an instance of my Rails model with Ajax.
It happens on the click of a button and my code is as shown below:
$("#button").click(function(){
$.ajax({
type: "POST",
url: "/slot_allocations/" + slotallocation_id,
dataType: "json",
data: {"_method":"delete"},
complete: function(){
$( "#SlotAllocationForm" ).dialog( "close" );
alert("Deleted successfully");
}
});
});
I am able to delete it successfully, however the delete
method is always followed up by a post
request to the server to create a new model with the existing data. These are the requests to the server.
1. POST http://localhost:3000/slot_allocations/1009 [HTTP/1.1 204 No Content 57ms]
2. POST http://localhost:3000/slot_allocations [HTTP/1.1 302 Found 111ms]
3. GET http://localhost:3000/slot_allocations/1010 [HTTP/1.1 200 OK 185ms]
#1
happens on the click of my button. However, I am not too sure why #2
and #3
occur.
There are two buttons in the view:
<button id="button">Delete</button>
<div class="actions"><%= f.submit %></div>
Assuming your button is inside of a form, clicking it is probably submitting that form in addition to firing the ajax request.
What you want to do is prevent the default action of clicking the button, which is submitting the form.
Change the function()
parameter to function(event)
, then add an event.preventDefault()
call:
$("#button").click(function(event){
$.ajax({
type: "POST",
url: "/slot_allocations/" + slotallocation_id,
dataType: "json",
data: {"_method":"delete"},
complete: function(){
$( "#SlotAllocationForm" ).dialog( "close" );
alert("Deleted successfully");
}
});
event.preventDefault();
});
You can use:
type: "DELETE"
instead of:
type: "POST"
and remove
data: {"_method":"delete"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With