I have the following jQuery code to intercept a form submission and turn it into an Ajax call:
$("form.section_change").off("submit").on("submit", function () {
var section = $(this).attr("data-section");
var initializer = $(this).attr("data-initfunc");
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
error: function (a, b) {
debugger;
},
success: function (result) {
$("div#" + section).html(result);
bindExtenders();
if (initializer != null) {
var func = window[initializer];
func();
}
}
});
return false;
});
Conceptually, what happens is the ajax call returns with html which is used to replace a div that’s within the form tag. The bindExtenders() function call “rebinds” the jQuery bindings, including the one that is described by this snippet. The initializer function is an optional item that runs a specified javascript function.
When I submit the form the first time I’m on the page the callback is called just once, as expected. However, on subsequent submissions the callback is called multiple times (usually twice, but sometimes more than that).
I’d like to figure out how to do this so the callback only gets called once.
You can do something like this:
This way you don’t need to rebind. See here: jQuery