I'm working on single page app using codeigniter and jquery, by clicking on a menu, i'm loading the content, and this works fine, the first time content is loaded, and when I try to submit a modal form it works, but every time I reload the content and I submit again the same form, I saw that it was submited the number of times I've reloaded the content on the page.
this is how I load the main content to the container when I click on the menu item :
case 'Parametrage':
$("#container").empty();
$("#container").load("params");
break;
and the script in view loaded by "param" controller that submits the modal form :
$(function(){
$('body').on('submit', 'form', function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "<?php echo site_url("params/save_form"); ?>",
data:$(this).serialize(),
success: function(response){
if(response == 'true'){
$.modal.close();
var table = $('#table_id').DataTable();
table.ajax.reload();
$('#dialog-message').attr('title','Enregistrement');
$('#msgIcon').attr('class','ui-icon ui-icon-circle-check');
$('#msgMessage').html('Enregistré avec succès');
$("#dialog-message").dialog({
modal: true,
buttons: {
Ok: function() {
$(this).dialog("close");
}
}
});
}else{
$('#errors_container').html(response);
}
},
error: function(){
alert('Error');
}
});
});
});
Can you help please ?
Thanks
Starting from Shaiful Islam answer, this solves the problem :
case 'Parametrage':
$("#container").empty();
//Added this line
$('body').off("submit", "form");
$("#container").load("params");
break;
Each time you load the main content it seems you javascript also loading with it. So change event is binding each time with your form.You need remove previous binding each time you load the main content.
Just add this line before $('body').on('submit', 'form', function(e){
$(body).off("submit", "form");
It will off your previous binding and keep one binding alive.
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