POST problem using JQuery

0

I'm studying JQuery and I'm having a problem with giving POST to an API that I have.

Follow 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 code in javascript

 //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 do not know why it is not giving more. It is always falling in error . I know my api is working because testo using Postman and POST works beautifully. Can anyone help me?

In chrome, this and adicionar appears this . I do not know if the answer is there.

    
asked by anonymous 15.03.2017 / 01:59

1 answer

2

If your $ ("# btn-submit") is an input submit, switch to: button. (=

    
15.03.2017 / 19:49