How to receive data in JSON (REST)

0

Hello, I'm learning to program, I'm in the first semester of development and I'm being charged at work to learn how to do it, and I'd like to know if what I did is right or not.

<!DOCTYPE html>
<html lang="pt-br" dir="ltr">

<head>
 <meta charset="utf-8">
 <title>Formulário de cadastro</title>
 <link rel="stylesheet" href="css/form.css">
</head>

<body>
<div class="container">

<h1>Formulário de cadastro</h1>

<form name="form" id="form" class="cadastro" action="" method="post" onsubmit="return validarForm();" required>

  <div class="grupoform">
    <label for= "Nome">Nome: </label>
    <input type="text" id="nome" name="nome" placeholder="Digite seu nome completo..." required>
  </div>

  <div class="grupoform">
    <label for="Senha">Senha: </label>
    <input type="password" id="senha" placeholder="Digite sua senha" required>
  </div>

  <div class="grupoform">
    <label for="senhanovamente">Confirme sua senha: </label>
    <input type="password" id="senhanovamente" placeholder="Digite sua senha novamente" required>
  </div>

  <div class="grupoform">
    <label for="cpf">CPF: </label>
    <input type="text" id="cpf" required>
  </div>

  <div class="grupoform">
    <label for="email">E-mail: </label>
    <input type="email" id="email" placeholder="jhon@emai l.com.br" required>
  </div>

  <div class="grupoform">
    <label for="cep">CEP: </label>
    <input type="text" id="cep" required>
  </div>

  <div class="grupoform">
    <label for="endereco">Endereço: </label>
    <input type="text" id="endereco" required>
  </div>

  <div class="grupoform">
    <label for="bairro">Bairro: </label>
    <input type="text" id="bairro" required>
  </div>

<div class="grupoform">
  <label for="complemento">Complemento: </label>
  <input type="text" id="complemento">
</div>

<div class="grupoform">
  <label for="cidade">Cidade: </label>
  <input type="text" id="cidade" required>
</div>

<div class="grupoform">
  <label for="estado">Estado: </label>
  <input type="text" id="estado" required>
</div>

<div class="grupoform">
  <label for="numero">Numero: </label>
  <input type="text" id="numero" required>
</div>


<div class="grupoform">
  <label for="telefone">Telefone: </label>
  <input type="text" id="telefone" placeholder=" DDD 999999999" required>
</div>

<div class="buttons">
  <button type="button" name="button" id="enviar">Enviar</button>
  <button type="reset" name="button">Limpar</button>
</div>
<div id="respostas">

</div>
  </form>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><scripttype="text/javascript" src="javascript/validacao.js"></script>
<script src="javascript/jquery.mask.js"></script>
<script src="javascript/ajax.js"></script>



</html>

Now the part of js

$("#enviar").click(function(){

  var nome = $("#nome").val();
  var cpf = $("#cpf").val();
  var email = $("#email").val();
  var rua = $("#endereco").val();
  var complemento = $("#complemento").val();
  var bairro = $("#bairro").val();
  var cep = $("#cep").val();
  var cidade = $("#cidade").val();
  var estado = $("#estado").val();
  var telefone = $("#telefone").val();
  var numero = $("#numero").val();
  var localidade =  {rua,complemento,bairro,cep,cidade,estado,numero};
  var investidor = {nome,cpf,email,localidade,telefone};


  $.ajax({
    url: "http://api.webhookinbox.com/i/LjzRS86F/in/",
    type: "POST",
    data: {"investidor":{"nome":nome, "cpf":cpf, "email":email, "localidade":{"rua":rua,"complemento":complemento,"bairro":bairro,"cep":cep,"cidade":cidade,"estado":estado,"numero":numero},"telefone":telefone}},
    contentType: "application/json",
    success: function(data){
      console.log(data.serialize());
  },
  error: function(error){
       console.log("Something went wrong", error);
   }
  });
});

pfvr, I need a lot of help, and I have no idea how to solve this ... the data in the webhook are being sent wrong, it was to send in JSON

(sorry for "leiguismo")

    
asked by anonymous 01.06.2018 / 19:16

1 answer

0

Using dataType: "json" you need to make sure that the server response is in JSON format, in the case of webhookinbox by default it only responds with OK text. As used above, the post will give error, however will return readyState: 4 and status: 200 . That means success, but as the response format is not in JSON catch it will be an error.

Observed the Jquery Docs :

  

dataType (default: Intelligent Guess (xml, json, script, or html))

     

Type: String

     

The type of data you are expecting back from the server. If none   is specified, jQuery will try to infer it based on the MIME type of   the response (an XML MIME type will yield XML, in 1.4 JSON will yield   a JavaScript object, in 1.4 script will execute the script, and   anything else will be returned as a string). The available types (and   the result passed as the first argument to your success callback) are:

...

  

"json": Evaluates the response as JSON and returns to JavaScript   object. Cross-domain "json" requests are converted to "jsonp" unless   the request includes jsonp: false in its request options. The JSON   data is parsed in a strict manner; any malformed JSON is rejected and   a parse error is thrown. As of jQuery 1.9, an empty response is also   rejected; the server should return a response of null or {} instead.   (See json.org for more information on proper JSON formatting.)

Try using the code below:

$("#enviar").click(function() {

    var nome = $("#nome").val();
    var cpf = $("#cpf").val();
    var email = $("#email").val();
    var rua = $("#endereco").val();
    var complemento = $("#complemento").val();
    var bairro = $("#bairro").val();
    var cep = $("#cep").val();
    var cidade = $("#cidade").val();
    var estado = $("#estado").val();
    var telefone = $("#telefone").val();
    var numero = $("#numero").val();
    var localidade = {
        rua,
        complemento,
        bairro,
        cep,
        cidade,
        estado,
        numero
    };
    var investidor = {
        nome,
        cpf,
        email,
        localidade,
        telefone
    };

    var dataJSON = {
        "investidor": {
            "nome": nome,
            "cpf": cpf,
            "email": email,
            "localidade": {
                "rua": rua,
                "complemento": complemento,
                "bairro": bairro,
                "cep": cep,
                "cidade": cidade,
                "estado": estado,
                "numero": numero
            },
            "telefone": telefone
        }
    };


    $.ajax({
        url: "https://api.webhookinbox.com/i/0HLzO6AL/in/",
        type: "POST",
        data: dataJSON,
        success: function(data) {
            console.log(data);
        },
        error: function(error) {
            console.log("Something went wrong", error);
        }
    });
});
    
02.06.2018 / 03:59