I have a form that is being submitted through ajax. It's not reloading the page, it just shows a success message, which is what I want. On my page I can have several forms with different ids but same class. I'm targetting the class for submit. But I have two different types of forms, new ones and existing ones (add or update basically). The update ones are working fine, but the add ones are giving me a browser alert when I try to exit the page. They think they are not already submitted.
Here's my code:
$("#simulation-table").on('submit', '.simulation_form', function(event){
event.preventDefault(); //prevent default action
var post_url = $(this).attr("action"); //get form action url
var request_method = $(this).attr("method"); //get form GET/POST method
var form_data = $(this).serialize(); //Encode form elements for submission
var form_id =$(this).attr("id");
$.ajax({
url : post_url,
type: request_method,
data : form_data
}).done(function(response){
response = JSON.parse(response);
if ((response.success === true || response.success == 'true') && (response.new === false || response.new == 'false')) {
alert_float('success', response.message);
$formSub = $('body').find('#' + form_id);
$formSub.find('.edit-field input').each(function () {
$(this).attr('readonly', true);
});
$formSub.find('.save_button button').prop('disabled', true);
} else {
alert_float('success', response.message);
$formSub = $('body').find('#' + form_id);
$formSub.find('.edit-field input').each(function () {
$(this).attr('readonly', true);
});
$formSub.find('.save_button button').prop('disabled', true);
$formSub.removeAttr('id');
$formSub.attr('id', 'simulation_form_' + response.insert_id);
$formSub.find('input[name="id"]').val(response.insert_id);
$formSub.attr('action', admin_url + 'leads/simulation/' + response.insert_id);
}
});
});
I have to change the form ids for the add function after receiving the success response, that's why I have that last piece of code. Why am I receiving this browser alert for changes not submitted?
My problem is not with the submit event, as it is triggering and completing successfully. The browser (Firefox in this case) is alerting me if I'm sure that I want to exit the page since some data might not be saved, but the form was submitted correctly.
EDIT: Updated code after marked as duplicate. Did not solve