POST problem using Jquery

Asked

Viewed 470 times

0

I’m studying Jquery and I have a little problem to give POST in an API I have.

Follows my html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title>Teste do Front End</title>    
    <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>
    <script src="javascript/ListarCategorias.js" type="text/javascript"></script>
  </head>
  <body>
    <h1>Hello, world!</h1>
    <div id="stage1" >
        <table id="stage2">
            <tr>
              <th id="CategoriaNome">Categorias</th>
              <th id="QtdeProdutos">Qtde Produtos</th>
              <th id="Acoes">Ações</th>
            </tr>
        </table>
    </div>
    <form id="cadCategoria">
      <label >Categoria</label>
      <input type="text" name="s" placeholder="Nome da Categoria" id="Nome">
      <input type="submit" value="Salvar" class="btn btn-primary" id="btn-submit">
    </form>
  </body>
</html>

Follow the javascript code

 //Listar usuarios
$(document).ready(function() {

    paginaGET = 'http://localhost:55119/private/obtertodas';
    paginaPOST = "http://localhost:55119/private/adicionar";

    $.ajax({  
        //type:'GET',        //Definimos o método HTTP usado
        url: paginaGET,//Definindo o arquivo onde serão buscados os dados
        dataType: 'json',   //Definimos o tipo de retorno
        cache: false,
        //se ocorrer um erro na chamada ajax, retorna este alerta
        //possiveis erros: pagina nao existe, erro de codigo na pagina, falha de comunicacao/internet, etc etc etc
        error: function() {
            alert('Erro: Alguma coisa deu errada ao retornar as Categorias... =(');
        },
        success: function(dados) {
            for(var i=0;dados.length>i;i++){  
                console.log(dados[i].CategoriaNome);
                document.getElementById('stage2').innerHTML += "<tr><td>"+dados[i].CategoriaNome+"</td><td>" + dados.length + "</td></tr>";
            }
        }
    });

    $("#btn-submit").click(function() {
        // var Categoria = new Object();
        // Categoria.CategoriaNome = $("#Nome").val();

        var Categoria = {
            CategoriaNome: $("#Nome").val()
        };

        $.ajax({
            type: "POST",
            url: paginaPOST,
            dataType: "JSON",
            data: Categoria,
            contentType: "application/json; charset=utf-8",
            success: function(data) {
                console.log("====== Categoria adicionada! ======");
            },
            error: function() { 
                alert("Algum erro no POST. Categoria lida: " + Categoria.CategoriaNome + " " + Categoria);
            }
        });
    });

    // $.getJSON(pagina, function(resp) {
    //     $.each(resp, function(key, value) {
    //        console.log(value.CategoriaNome);
    //        document.getElementById('stage2').innerHTML += "<tr><td>" + value.CategoriaNome + "</td><td>" + "</td></tr>";
    //     });
    // });
    });

Before it was working, but I don’t know why it’s not working anymore. It’s always falling in the error. I know my api is working because I test using Postman and POST works beautifully. Can anyone help me?

On Chrome, it appears this and in the adicionar appears this. I don’t know if the answer is there.

  • One of the reasons may be that the correct one is method: 'POST' instead of type: "POST". If this doesn’t work, see if there are any messages on the console.

  • @Lucascosta thank you for the comment, but it didn’t work. I’m still with the same result.

  • The problem is in the load or button ajax?

  • @Aline really do not know. I tried to do a test on this excerpt hereerror: function() { &#xA; alert("Algum erro no POST. Categoria lida: " + Categoria.CategoriaNome + " " + Categoria);&#xA; }. I know he’s reading what I write because it appears on error

  • You can test by replacing ajax parameters with: url: pageGET, , processData: false, contenttype: false, type: 'POST' ?

  • @Aline taking down the data: Categoria ? Or by adding the processData: false and changing the parameter of contentType for false?

  • If your method is waiting for a parameter with value, you will have to send it. Otherwise remove. Remove contenttype. I just want to know if you’re getting the method.

Show 3 more comments

1 answer

3


If your $("#btn-submit") for a input submit, change for: button.

  • Thanks Aline! The problem was that.

Browser other questions tagged

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