Search code examples
jqueryruby-on-railsbootbox

Rails delete link call from javascript


With rails I can do this:

<%= link_to("Delete", product, 
            :method => :delete, 
            data: {confirm: 'Are you sure?.'}
            id: 'discard_btn') %>

and I know that when the click is received, a standard javascript confirm dialog will ask the 'Are you sure?' question sending the request if an OK is clicked.

I want to change this plain dialog with a beautiful Bootbox confirm dialog with the same behavior. I tried to do this:

$('#employee_discard').click(function(e){
  bootbox.confirm("Are you sure?", function(result) {
    // How to send the delete request from this callback?
  });
  // Prevent the request to be sent.  This works/  
  return false;
});

But my problem is that Bootbox uses callbacks to handle its events and just writing a return true inside the callback will not work.

How can I send a delete request from javascript?


Solution

  • Something like this should work:

    $.ajax({
        type: "DELETE",
        url: "/products/1"
    })
    

    And in the controller you need to add a response in js format

    respond_to do |format|
      format.js { render "something.js.erb" }
    end
    

    Finally, the something.js.erb will be executed. For example, you can refresh the current page

    location.reload();