远程表单内嵌远程链接:仅提交触发AJAX回调问题咨询
The issue here is that both your form and nested link use remote: true, so Rails UJS fires AJAX events for both. Since DOM events bubble upward, your form's AJAX handlers are catching events from the link too. Here are two clean ways to fix this:
Option 1: Check Event Origin in Form Handlers
This approach verifies that the AJAX event originated from the form itself, not the nested link. It’s robust because it doesn’t depend on the link’s CSS classes.
jQuery -> # Handle form success $('.my-form').on 'ajax:success', (event) -> # Only run if the event came from the form submission if event.target is this # Replace with your success logic (show message, update UI, etc.) alert "Form saved successfully!" # Handle form errors $('.my-form').on 'ajax:error', (event) -> if event.target is this # Replace with your error logic alert "Failed to save form. Please try again."
How it works:
- When you submit the form,
event.targetwill be the<form>element (matchingthisin the handler). - When you click the remote link,
event.targetwill be the<a>element, so the condition fails and your callback doesn’t run.
Option 2: Stop Event Bubbling from the Remote Link
If you prefer, you can prevent the link’s AJAX events from bubbling up to the form. This is straightforward but requires targeting the link specifically.
jQuery -> # Form submission handlers (unchanged) $('.my-form').on 'ajax:success', -> alert "Form saved successfully!" $('.my-form').on 'ajax:error', -> alert "Failed to save form. Please try again." # Prevent link's AJAX events from reaching the form $('.my-form .btn-warning').on 'ajax:success ajax:error ajax:beforeSend', (event) -> event.stopPropagation()
How it works:
- We listen for key AJAX events on the nested link and call
event.stopPropagation()to stop them from bubbling up to the form. - This ensures only the form’s own AJAX events trigger your callbacks.
Which Option to Choose?
- Use Option 1 if you want a future-proof solution (works even if you change the link’s classes or structure).
- Use Option 2 if you prefer a more explicit separation between the form and link’s AJAX behavior.
Both approaches will ensure your success/error messages only appear when the user clicks the "Save" button, not when they click the nested remote link.
内容的提问来源于stack exchange,提问作者nattfodd

