I'm using the extensions methods @Ajax.BeginForm()
to save the data via AJAX. To prevent more than one click on the submit button, which could cause a double insert in my database, I decided to include a small snippet of code inside the jquery.unobtrusive-ajax.js file, which disables the submit button.
I include the code snippet just after the calls of the method that displays a loader, respectively loading.show(duration);
and loading.hide(duration);
.
Here is the complete method where I added my code:
function asyncRequest(element, options) {
var confirm, loading, method, duration;
confirm = element.getAttribute("data-ajax-confirm");
if (confirm && !window.confirm(confirm)) {
return;
}
loading = $(element.getAttribute("data-ajax-loading"));
duration = parseInt(element.getAttribute("data-ajax-loading-duration"), 10) || 0;
$.extend(options, {
context: element,
type: element.getAttribute("data-ajax-method") || undefined,
url: element.getAttribute("data-ajax-url") || undefined,
beforeSend: function (xhr) {
var result;
asyncOnBeforeSend(xhr, method);
result = getFunction(element.getAttribute("data-ajax-begin"), ["xhr"]).apply(this, arguments);
if (result !== false) {
loading.show(duration);
$("form[data-ajax=true] :submit").attr('disabled', 'disabled').addClass('disabled'); //adicionado para evitar novo clique após submit
}
return result;
},
complete: function () {
loading.hide(duration);
$("form[data-ajax=true] :submit").removeAttr('disabled').removeClass('disabled'); //adicionado para evitar clique após submit
getFunction(element.getAttribute("data-ajax-complete"), ["xhr", "status"]).apply(this, arguments);
},
success: function (data, status, xhr) {
asyncOnSuccess(element, data, xhr.getResponseHeader("Content-Type") || "text/html");
getFunction(element.getAttribute("data-ajax-success"), ["data", "status", "xhr"]).apply(this, arguments);
},
error: getFunction(element.getAttribute("data-ajax-failure"), ["xhr", "status", "error"])
});
options.data.push({ name: "X-Requested-With", value: "XMLHttpRequest" });
method = options.type.toUpperCase();
if (!isMethodProxySafe(method)) {
options.type = "POST";
options.data.push({ name: "X-HTTP-Method-Override", value: method });
}
$.ajax(options);
}
The excerpts that include:
loading.show(duration);
$("form[data-ajax=true] :submit").attr('disabled', 'disabled').addClass('disabled');
e:
loading.hide(duration);
$("form[data-ajax=true] :submit").removeAttr('disabled').removeClass('disabled');
That adds and removes a disabled="disabled"
attribute and a class also disabled
to the submit button just after the loading element is displayed and hidden.
This works perfectly, the only problem is that since I am editing a code that Microsoft maintains, if a new version of the file is published, I will lose my code. So my question is about whether it is possible to create a similar effect, with some extension of that file, that could be written in a separate script in a separate file.