Matthew,
One of the problems with your code is that it will call the AJAX request regardless of whether the form is valid or not. The way things are, you only do the validation after you send the data to the server, which is hardly a good thing to do. The code below solves this problem, based on your code.
function validarLivro() {
var nome = $("#nomelivro").val()
var descricao = $("#descricao").val()
var genero = $("#genero").val()
var autor = $("#autor").val()
var editora = $("#editora").val()
/* A função .val() do jQuery retornará undefined se o campo estiver vazio.
Podemos fazer assim então para verificar se todos os campos estão preenchidos */
if(nome && descricao && genero && autor && editora) {
// Se todos os campos estiverem preenchidos, passamos um objeto livro para o cadastro
return {
op: "cadastra",
nomelivro: nome,
descricao: descricao,
genero: genero,
autor: autor,
editora: editora
}
} else {
return false
}
}
function cadastrarLivro() {
const livro = validarLivro()
if(livro) {
// Código para chamar a requisição e salvar o livro
$.ajax({
type: 'POST',
datatype: 'json',
url: api,
data: livro
})
// Vai ser chamado caso tudo ocorra normalmente
.done(function (msg) {
cadastrado=JSON.parse(msg);
$("#CadLivros").addClass("hide");
$("#telaPrincipal").removeClass("hide");
})
// Vai ser chamado em caso de erro no servidor
.fail(function () {
alert("Um erro ocorreu!")
})
} else {
// Caso o livro não tenha passado na validação trate o erro aqui
M.toast({html: 'Um dos campos está vazio!'});
}
}
Now just call cadastrarLivro()
and everything should work normally.
Hug
P.S.: Another problem of your code that I had the freedom to fix, this is more a matter of reading is the fact of you, is the presence of a Codesmell in the function’s nomenclature. It has the name validarCadastro but at the same time it does this and also makes the request on the server. Separating code avoids this problem ;)
Hello @Your welcome to Stackoverflow, to complement your question I suggest you add the error generated on the server if any error is generated, it would also be interesting for you to show what the persistence code on the server (has the server been tested and is working normally?), I suggest you see [mcve]
– Lucas Duete
Thank you very much Ucas, is giving some errors in the server, but we will fix it
– Mateus Santos
Matthew, what error is going on? What I can see passing the quick eye on the code is that in the data, in
nomelivro
, you are pointing to a variable that does not exist. It should benomelivro: nome
. Other than that, what is coming back from the server? The more information you pass on, the better it is for us to help you and pass an accurate solution– João Pedro Henrique