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">×</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.
You CAN include a modal within a form. In the Bootstrap documentation it recommends the modal to be a "top level" element, but it still works within a form. You create a form, and then the modal "save" button will be a button of type="submit" to submit the form from within the modal.
We can submit a form by ajax using submit button and by mentioning the values of the following parameters. type: It is used to specify the type of request. url: It is used to specify the URL to send the request to. data: It is used to specify data to be sent to the server.
AJAX form submitting allows you to send data in the background, eliminating the need to reload websites to see the updates. This makes the user experience much smoother.
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;
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With