I am currently working on a project that involves saving data from a form into a database. The aim is to verify if the data entered is correct (having a necessary key and at least one value), as well as checking if the key already exists in the database. While the initial part of validating parameters has been completed successfully, I am facing an issue with submitting the form. Below is the code snippet:
function insertControl() {
var insertError= $("#insertError");
var key = $.trim($("input[id='key']").val());
var value1 = $.trim($("textarea[id='valueITA']").val());
var value2 = $.trim($("textarea[id='valueGBR']").val());
var value3 = $.trim($("textarea[id='valueAUS']").val());
var value4 = $.trim($("textarea[id='valueUSA']").val());
var value5 = $.trim($("textarea[id='valueFRA']").val());
var id = $.trim($("input[id='control']").val());
var controlled= $.trim($("input[id='controlled']").val());
event.preventDefault();
if (key === "") {
if (value1 === "" && value2 === "" && value3 === "" && value4 === ""
&& value5 === "") {
insertError
.html("KEY required<br>at least a value required");
} else {
insertError.html("KEY required");
}
} else {
insertError.html("");
if (value1 === "" && value2 === "" && value3 === "" && value4 === ""
&& value5 === "") {
insertError.html("at least a value required");
} else {
if (id == "") {
if (controlled == "") {
return control();
} else if (controlled== 'ok') {
if (!confirm('are you sure?'))
return e.preventDefault();
document.getElementById('form').submit();
}
} else {
if (id != "") {
if (!confirm('are you sure??'))
return e.preventDefault();
document.getElementById('form').submit();
}
}
}
}
};
If the form is correctly filled out and there is no ID present (indicating the creation of a new record instead of editing), it triggers a function that initiates an AJAX call. This call checks the provided key against existing records in the database through a servlet and returns JSON data.
Below is the corresponding code for this functionality:
function control() {
$
.ajax({
url : 'edit',
data : {
key : $('#key').val()
},
success : function(data, status, xhr) {
var insertError = $("#insertError ");
var labels = data.length;
if (labels == 0) {
$('#controlled').val('ok');
return insertControl();
} else if (dati > 0) {
insertError
.html("this key is already used");
return event.preventDefault();
}
},
error : function(req, status, err) {
console.log('Something went wrong', status, err);
}
})
The verification process functions correctly but the submission fails when creating a new label. Editing, however, manages to submit without issues. I have integrated this function using the onsubmit attribute within the HTML file.