You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

远程表单内嵌远程链接:仅提交触发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.target will be the <form> element (matching this in the handler).
  • When you click the remote link, event.target will be the <a> element, so the condition fails and your callback doesn’t run.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:40:52