Why does remote: true and confirm: 'Are You Sure?' not work together?
Asked Answered
R

1

5

I have been wrestling with Rails 4 and UJS and noticed that Rails 4.1 doesn't behave (specifically, rails-ujs) the way I would expect.

When using a remote link with a confirmation dialog, the UJS driver sends the XHR before the confirmation popup is approved (making the confirmation popup pointless). I would have expected Rails to be able to handle this combination of options, but I had to write my own javascript to perform the confirmation popup and hook onto the "ajax:beforeSend" event to prevent the request from firing too soon.

Here's what I had that did not work (request fired immediately, did not wait for confirm dialog to return true):

= link_to 'Ajax Button', app_path(resource), method: :delete, 
    remote: true, id: 'ajax_link', disable_with: 'Wait...',
    confirm: 'Are you sure?'

Here's what I have now that does work:

= link_to 'Ajax Button', app_path(resource), method: :delete,
    remote: true, id: 'ajax_link', disable_with: 'Wait...'

$ ->
  $("a[data-remote]#ajax_link").on 'ajax:beforeSend', (xhr, settings) ->
    return confirm("Are you sure?")

Is it just me or shouldn't rails/jquery-ujs handle the above combination of options and wait for the confirmation popup? In the past, Rails 3 and prior, the remote links/buttons usually "just worked" when it came to AJAX and remote requests, but it seems with Rails 4 that working with AJAX requires a bit more finesse that was previously required.

Has anyone else experienced this with Rails 4.1? Any other solutions out there?

Rhenium answered 16/8, 2014 at 3:1 Comment(2)
Try = link_to 'Ajax Button', app_path(resource), method: :delete, remote: true, id: 'ajax_link', data: { disable_with: "Wait..." }, data: { confirm: 'Are you sure?' }.If it works i will post it as an answer.Bugbee
Thanks @pavan, thats definitely a thought. The syntax I used is technically deprecated so I'll give your solution a go and see if that makes it work the way I expected.Rhenium
B
10

The below should work

= link_to 'Ajax Button', app_path(resource), method: :delete, remote: true, id: 'ajax_link', data: { disable_with: "Wait..." }, data: { confirm: 'Are you sure?' }
Bugbee answered 6/12, 2015 at 6:55 Comment(3)
Any suggestion with regards to a f.sumbit? I feel like I'm experiencing the same behavior as the original question but have not been successful with this approach.Matinee
Perfect Answer!!Ribaldry
This should be rewrite: ``` = link_to 'Ajax Button', app_path(resource), method: :delete, remote: true, id: 'ajax_link', data: { disable_with: "wait...", confirm: 'Are you sure?' } ```Worshipful

© 2022 - 2024 — McMap. All rights reserved.