I’m writing a module that has multiple questions users can chose to answer. Each has their own submit button that causes the data to be posted to my application, displays the results, and then removes the form. I was able to get this piece working perfectly but if I add a button that allows the users to submit all the forms at once it submits the form data correctly but the results get appended to the last question (the items are getting the correct data). This is the javascript/jQuery code that I’m using:
// setup the save answer click handler
$(document).on('click', '.saveAnswer', function(event){
event.preventDefault();
// get the form
form = $(this).closest('form');
$.ajax({
async:true,
type: 'POST',
url: form.attr('action'),
data: form.serialize(),
success: function(data){
// append the text to the bottom of the answers
form.closest('.question').find('.answers').append('<li>' + data + '</li>').hide().slideDown(500);
form.slideUp(500,function(){
form.remove();
});
}
});
});
// setup the save all answer click handler
$(document).on('click', '.saveAll', function(){
$('.saveAnswer').trigger('click');
});
If I change the async value to false then it works correctly but none of the animations work and the page seems to freeze for a second until all the answers are submitted.
After some debugging I found that the form variable gets overwritten each time the function is run. Is there a way to prevent this from happening?
formis a global (or at least a higher-scope) variable, which means each call to the handler tramples on the old value, and thesuccess/errorcallbacks all share the same value.Make it local (
var form = $(....);), so that each invocation of the handler has its own value.