Ajax form sending before submit
(function registerDragParameters()
{
$(document).ready(function() {
var $editForm = $('button[name=btn_update_and_edit], button[name=btn_update_and_list]').parents('form:first');
function isParameterValid(paramValue) {
var protoParams = availableParameters.filter(function(entry) {
return entry.value == paramValue;
});
return protoParams[0];
}
function loadDragParametersFromAllInstances(parameters) {
for(var instanceName in CKEDITOR.instances) {
var parametersTextInOneInstance =
$(CKEDITOR.instances[instanceName].window.getFrame().$)
.contents()
.find('.drag-parameter-inside')
.map(function() {
return $.trim($(this).text());
}).get();
Array.prototype.push.apply(parameters, parametersTextInOneInstance);
}
}
function registerParametersCall(parameters) {
var currentTemplateId = $('form[method="post"] input.template-id').val();
$.ajax({
type: "PUT",
contentType: "application/json",
url: "/api/template/" + currentTemplateId +"/parameters",
data: JSON.stringify(parameters),
complete: function(xhr, textStatus) {
if (xhr.status != 200) {
alert('Sorry, we have a problem with template administration');
} else {
// detach handler and submit form data
sendForm();
}
}
});
}
function sendForm()
{
$editForm.off("submit");
$editForm.submit();
}
$editForm.submit(function(e) {
e.preventDefault();
if(window.localStorage !== undefined) {
var parameters = [];
if (isCKEditorPresent()) {
loadDragParametersFromAllInstances(parameters)
} else {
alert('Please wait until CKEditor has been loaded');
e.preventDefault();
return;
}
if (parameters.length > 0) {
var paramsOnRegistration = [];
parameters.forEach(function (param) {
var protoParam = isParameterValid(param);
if (protoParam != null) {
paramsOnRegistration.push(protoParam);
}
});
if (paramsOnRegistration.length > 0) {
registerParametersCall(paramsOnRegistration);
}
} else { sendForm(); }
} else { alert("Browser Local storage failed. Try refreshing your browser"); }
});
});
})();