Submitting modal form via Ajax

ajax, forms, jquery, symfony, twitter-bootstrap

Solution

It looks like your firing this on the submit event, which is why its....submitting? Maybe this would work better?

$(function() {

$('#tag-form-submit').on('click', function(e) {
    e.preventDefault();
    $.ajax({
        type: "POST",
        url: "{{ path('addTag') }}",
        data: $('form.tagForm').serialize(),
        success: function(response) {
            alert(response['response']);
        },
        error: function() {
            alert('Error');
        }
    });
    return false;
});
});

Problem

I have a normal form for my question entity. Within that form is a modal form which allows users to add additional tags for their question. Here is an image of my modal form: Here is my twig template for my modal form: ``` <div id="mymodal" class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h4 class="modal-title" id="myModalLabel">Add New Tag</h4> </div> <form class="tagForm" id="tag-form" action="{{ path('addTag') }}" method="post" enctype="multipart/form-data"> <div class="modal-body"> <label for="tagName">Tag Name: </label> <input id="tagName" class="form-control" type="text"/> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <input id="tag-form-submit" type="submit" class="btn btn-primary" value="Add Tag"> </div> </form> </div> </div> ``` Script for viewing my modal form: ``` $('#addTag').click(function(e) { e.preventDefault(); $('#mymodal').modal(); }); ``` Script for my modal form submission: ``` $(function() { $('#tag-form').submit(function() { $.ajax({ type: "POST", url: "{{ path('addTag') }}", data: $('form.tagForm').serialize(), success: function(response) { alert(response['response']); }, error: function() { alert('Error'); } }); return false; }); }); ``` My problem is that everytime I click the add tag button, all the forms including the question form is also submitted. What I really want is just to submit the modal form.

Original source