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

Rails中Google Maps结合Magnific Popup表单二次提交失效求助

Fixing Magnific Popup Form Submission Issue in Rails + Google Maps

Hey Andrew, I’ve run into this exact snag before with dynamic forms and Magnific Popup—let’s break down why this is happening and how to fix it.

Why This Happens

The core issue is event binding on dynamic DOM elements. When you first open the popup, your form renders and your submit event listener attaches to it. But after you submit and close the popup, that form’s DOM element gets destroyed. The second time you open the popup, a brand new form is created, but your original event listener is still tied to the old (now removed) element—so clicking submit does nothing.

Solutions

1. Use jQuery Event Delegation (Most Reliable)

Instead of binding the submit event directly to the form, bind it to a parent element that exists on the page from load time (like document or your map container). This way, any new forms added dynamically will trigger the event automatically.

Here’s how to adjust your JavaScript:

// Initialize Magnific Popup on map click
$(document).on('click', '#your-map-element', function(e) {
  const lat = e.latLng.lat();
  const lng = e.latLng.lng();

  $.magnificPopup.open({
    items: {
      // Load your form via AJAX, passing the clicked coordinates
      src: `/markers/new?lat=${lat}&lng=${lng}`,
      type: 'ajax'
    },
    callbacks: {
      ajaxContentAdded: function() {
        // Set hidden latitude/longitude fields with the clicked values
        $('#marker_latitude').val(lat);
        $('#marker_longitude').val(lng);
      }
    }
  });
});

// Handle form submission with event delegation
$(document).on('submit', '.map-popup-form', function(e) {
  e.preventDefault();
  const $form = $(this);

  $.ajax({
    url: $form.attr('action'),
    method: $form.attr('method'),
    data: $form.serialize(),
    success: function(response) {
      // Close the popup on successful submission
      $.magnificPopup.close();
      // Add the new marker to your Google Map
      new google.maps.Marker({
        position: { lat: response.latitude, lng: response.longitude },
        map: yourMapInstance // Replace with your actual map variable
      });
    },
    error: function(xhr) {
      // Replace the popup content with the form containing error messages
      $form.replaceWith(xhr.responseText);
    }
  });
});

2. Adjust Turbo Settings (If Using Rails 7+)

If your Rails app uses Turbo (the default in Rails 7), Turbo might interfere with form submissions or DOM updates. Try these tweaks:

  • Add data-turbo="false" to your form to disable Turbo’s default submission handling:
    <%= form_with(model: @marker, html: { class: 'map-popup-form' }, data: { turbo: 'false' }) do |form| %>
      <!-- Your form fields here -->
      <%= form.label :name %>
      <%= form.text_field :name %>
    
      <%= form.hidden_field :latitude %>
      <%= form.hidden_field :longitude %>
    
      <%= form.submit "Create Marker" %>
    <% end %>
    
  • If you want to keep Turbo enabled, listen for the turbo:submit-end event to close the popup after submission:
    $(document).on('turbo:submit-end', '.map-popup-form', function() {
      $.magnificPopup.close();
    });
    

3. Re-Bind Events in Magnific Popup’s Callback

Another option is to re-attach your submit event listener every time the popup loads new content, using Magnific Popup’s ajaxContentAdded callback:

$.magnificPopup.open({
  items: { /* ... */ },
  callbacks: {
    ajaxContentAdded: function() {
      // Re-bind the submit event to the new form (unbind first to avoid duplicates)
      $('.map-popup-form').off('submit').on('submit', function(e) {
        e.preventDefault();
        // Your submission logic here
      });
    }
  }
});

Note: This works but is less clean than event delegation, since you have to manually unbind/rebind events each time.

Quick Checks to Verify

  • Open your browser’s DevTools (F12) and check the Console for any JavaScript errors that might be blocking the submit action.
  • Inspect the form element after opening the popup the second time—make sure it has the correct action and method attributes.
  • Confirm that your Rails controller’s create action is correctly responding with JSON (or HTML, depending on your setup) after submission.

内容的提问来源于stack exchange,提问作者Andrew Fleischer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:39:48