Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Ajax Jquery Delete Submits a Post request after

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>
like image 711
Butter Beer Avatar asked Feb 17 '13 17:02

Butter Beer


2 Answers

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();
});
like image 134
Dylan Markow Avatar answered Oct 21 '22 16:10

Dylan Markow


You can use:

type: "DELETE"

instead of:

type: "POST"

and remove

data: {"_method":"delete"}
like image 31
Masolino Avatar answered Oct 21 '22 16:10

Masolino