Creation of product registration with javascript

Asked

Viewed 1,151 times

1

I am unable to register a book in an app that I am creating, this validation with ajax is correct?

<b>var cadastrado = null;</b>

<b>
function ValidarLivro (){
    var nome  = $("#nomelivro").val();
    var descricao = $("#descricao").val();
    var genero = $("#genero").val();
    var autor = $("#autor").val();
    var editora =$("#editora").val();
    </b>    


    $ajax({
        type:'POST',
        datatype:'json',        
        url:api,
        data:{op:"cadastra", nomelivro: nomelivro, descricao: descricao,genero: genero,autor: autor,editora: editora }
    })
    .done(function(msg){
        if (msg!=""){
            cadastrado=JSON.parse(msg);
            $("#CadLivros").addClass("hide");
            $("#telaPrincipal").removeClass("hide");
        } else {
            M.toast({html: 'Um dos campos está vazio!'});
        }
   });  
}
  • 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]

  • 1

    Thank you very much Ucas, is giving some errors in the server, but we will fix it

  • 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 be nomelivro: 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

1 answer

0

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 ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.