I'm 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>
on confirmation, but can't figure out a clean way to do it.
Problems with existing solutions:
disable_with:
If I add :disable_with => '<span>Saving...</span>'
the inner HTML of the link will be replaced instead of the link itself. Don't want that.
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 fits with Rails 3 UJS best practices?
You can use the hook ajax:beforeSend
:
$('a#my_link_to').bind('ajax:beforeSend', function(evt, xhr, settings) {
$(this).replaceWith('<span>Saving...</span>');
})
And then you could add a bind 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 refer the comment below which also is very important
I think this is a case where the functionality you want goes beyond what's offered by Rails' JS helpers. At this point I would just avoid using the :confirm and :remote options to link_to, and implement it in plain jQuery UJS or similar.
You might also think in terms of hiding the link and showing the 'Saving...' span when the user confirms, rather than replacing html; I think it will end up simpler that way, and still give you the effect you're looking for.
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