twitter-bootstrapsubmitmodal-dialog

Form inside a Bootstrap modal


I have a modal that makes the registration of products. I wanted to submit a form inside the modal without leaving the modal.

<!-- Button to trigger modal -->
<a href="#myModal" role="button" class="btn" data-toggle="modal">Launch demo modal</a>
 
<!-- Modal -->
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3 id="myModalLabel">Modal header</h3>
  </div>
  <div class="modal-body">
    <form method="post">
        <button type="submit">Submit</button>
    </form>
  </div>
  <div class="modal-footer">
    <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
    <button class="btn btn-primary">Save changes</button>
  </div>
</div>

Solution

  • Firstly, set an id on your <form> tag:

    <form id="myForm" method="post">
        ...
    </form>
    

    If you were using jQuery (highly recommended), you could do this:

    $(function(){
        $('#myForm').on('submit', function(e){
          e.preventDefault();
          $.post('http://www.somewhere.com/path/to/post', 
             $('#myForm').serialize(), 
             function(data, status, xhr){
               // do something here with response;
             });
        });
    });