How to receive data in JSON (REST)

Asked

Viewed 1,364 times

0

Hello, I am learning to program, I am in the 1 semester of development and I am being charged at work to learn how to do this, and I would 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>
<script type="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 really need help, and I have no idea how to solve this... the data in the webhook is being sent wrong, was to send in JSON

(sorry for the "layman")

1 answer

0

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

Observed the Docs from Jquery:

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

Type: String

The type of data that you’re 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 a 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);
        }
    });
});
  • then, there is some "webhookinbox" that gets in JSON ?

  • With this code, it gave the same thing that I had achieved, only that even so, it does not go in JSON

  • It goes in JSON yes, the server response that is not in JSON. Try to use and create a service with: https://www.mockable.io/

  • I got by the webhook, I just need to know how to get the %5b and %5d out, and replace them with the couchetes

Browser other questions tagged

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