Rails link_to: do something after confirmation

I am trying to execute a save action via AJAX using link_to :

 <%= link_to 'Save', image_path(image), method: :patch, data:{ confirm: 'Save image?', remote: true } %> 

I want the link to be replaced with <span>Saving...</span> upon confirmation, but cannot figure out how to do this.

Problems with existing solutions:

disable_with:
If I add :disable_with => '<span>Saving...</span>' , the internal HTML of the link will be replaced instead of the link itself. I do not want this.

OnClick:
If I add :onclick => "$(this).replaceWith('<span>Saving...</span>');" , the link will be replaced immediately, even if the user cancels the confirmation

Is there a solution that matches the best practices of Rails 3 UJS?

+6
source share
5 answers

You can use ajax:beforeSend :

 $('a#my_link_to').bind('ajax:beforeSend', function(evt, xhr, settings) { $(this).replaceWith('<span>Saving...</span>'); }) 

And then you can add the binding to ajax:success :

 $('a#my_link_to') .bind('ajax:beforeSend', function(evt, xhr, settings) { $(this).replaceWith('<span id="saving">Saving...</span>'); }) .bind('ajax:success', function(evt, data, status, xhr) { $('span#saving').replaceWith('Saved!'); }) 

Note. Please see the comment below, which is also very important.

+5
source

I think this is the case when the functionality you want goes beyond what the JS Rails helpers offer. At this point, I simply will not use the: confirm and: remote options for link_to and implement it in plain jQuery UJS or similar.

You may also think in terms of hiding the link and displaying the "Save ..." range when the user confirms rather than replaces html; I think that in the end it will be easier, and still give you the effect you are looking for.

+1
source

I think you should use confirmation: full event. (more details: https://github.com/rails/jquery-ujs/blob/master/src/rails.js )

0
source

Here is how I did it:

 <%= link_to 'Save', image_path(image), method: :patch, data:{ confirm: 'Save image?', remote: true }, onclick: "$(this).one('ajax:beforeSend', function(e) { $(this).replaceWith('<span>Saving...</span>'); });" %> 

(The problem with this solution is that the handlers accumulate if the user clicks, doesn't confirm, clicks again, etc. Therefore, it's not perfect ...)

0
source

You can use the confirm:complete event. It receives a second boolean argument, which indicates whether the result was canceled or ok.

0
source

Source: https://habr.com/ru/post/952516/


All Articles