I try to post a form using ajax the current code does not really work. When I press the save button the form get submitted n + 1 times. ie After refreshing the page it submit once, next time I submit two form get submitted, third time... etc.
I have spend a lot of time researching this already (2 days) and I have not found a questions quite similar to what I am asking.
I am on a steep learning curve here so I hope someone can point out to me what I am doing wrong.
I think I might have mixed something up. The steps up to submit is.
$('#confirmYes').click(function() { $('#confirm-object').modal('hide'); // close confirm modal $('#newForm').submit(function (e) { e.preventDefault(); let formData = $(this).serialize(); $.post({ type: 'POST', url: '/api/pois/', data: formData })
<form id="newForm"> <input type="text" id="name" name="name"> <input type="text" id="company" name="company"> </form> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button> <button type="submit" class="btn btn-success" form="newForm" id="confirmYes">Save</button> </div>
Simply remove the $('#newForm').submit(function (e) {});
:
.submit(function (e) {})
is creating an event handler for the submit
event of your form, it's not submitting it.
$('#confirmYes').click(function() {
$('#confirm-object').modal('hide'); // close confirm modal
let formData = $('#newForm').serialize();
$.post({
type: 'POST',
url: '/api/pois/',
data: formData
});
});
The issue is because you are creating a new submit
event handler in every click. From the description of what you want to do, you instead need to create a single submit handler when the page loads, and trigger it when the button is clicked. Something like this:
$('#newForm').submit(function(e) { // handle the submit event
e.preventDefault();
let formData = $(this).serialize();
$.post({
type: 'POST',
url: '/api/pois/',
data: formData
})
})
$('#confirmYes').click(function() {
$('#confirm-object').modal('hide');
$('#newForm').submit(); // trigger the submit event
});
$('#confirmYes').click(function() { let formData = $('#newForm').serialize(); $.post({ type: 'POST', url: '/api/pois/', data: formData }); );
<form id="newForm"> <input type="text" id="name" name="name"> <input type="text" id="company" name="company"> </form> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button> <button type="button" class="btn btn-success" id="confirmYes">Save</button> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.