0

I'm having trouble submitting this merged forms. If I use the mainForm.submit() which is commented out now, it submits, but when I use submit with $.ajax it doesn't reach success. I tried also mainForm[0].submit(function() {...} without any luck. Can somebody help me with that?

$(function() {
  var mainForm = $('#mainForm'),
        modalForm = $('#modalForm');


  $('#submitBtn').on('click', function() {
    //mainForm.submit();
    
    console.log($('#mainForm, #modalForm').serialize());

    mainForm.submit(function() {
      var action = $(this).attr('action');

      $.ajax({
        url: action,
        type: 'POST',
        data: $('#mainForm, #modalForm').serialize(),
        success: function() {
          console.log('success');
          //window.location.replace(action);
        }
      });
      return false;
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form id="mainForm" action="/page/2" method="post">
  <input type="hidden" name="amount" value="1" />
  <input type="hidden" name="currency" value="USD" />
  <input type="hidden" name="recurring" value="true" />
</form>

<div class="modal">
  <form id="modalForm">
    <input type="text" name="firstName" value="Foo" />
    <input type="text" name="lastName" value="Bar" />
    <input type="text" name="emailAddress" value="foo.bar@domain.com" />
  </form>
  
  <button type="button" id="submitBtn">Send</button>
</div>
levipadre
  • 569
  • 7
  • 31

1 Answers1

1

I think there is no need to use submit, just use ajax on clicked button function:

$(function() {
  $('#submitBtn').on('click', function() {
      var action = $('#mainForm').attr('action');

      $.ajax({
        url: action,
        type: 'POST',
        data: $('#mainForm, #modalForm').serialize(),
        success: function() {
          console.log('success');
          //window.location.replace(action);
          return true;
        }
      });
      return false;
  });
});
Navand
  • 446
  • 4
  • 11
  • OMG, you are so right! How could I miss that?! Thanks @Navand! – levipadre Mar 09 '21 at 18:35
  • One remaining question about the script. If the url is defined by the action attribute, why do I need the window.location.replace(action)? Without it it doesn't go to the next page. – levipadre Mar 09 '21 at 21:48
  • As I know, If you don't want to move user to new location or refresh the page, You use ajax, otherwise you normally submit your form with form.submit, that post your data and also redirect user to new address, check [this](https://stackoverflow.com/questions/17809056/how-to-add-additional-fields-to-form-before-submit) for update form before submit. – Navand Mar 11 '21 at 14:45