Form completion with return of a json

Asked

Viewed 1,569 times

8

I am using a webservice (viaCep) for automatic filling of the backyard, for when the user type a zip code. The webservice returns me a json with the information from the patio, and from that return I fill the inputs (Street, city, etc..).

When I manually type the information of the address fields, I can get it in the request.

When fields are filled in with information from the Webservice, when retrieving the request from the form, the fields (City, State, Street, etc.) arrive null.

Javascript that returns the json webservice:

function limpa_formulário_cep() {
   document.getElementById('endereco').value = ("");
   document.getElementById('bairro').value = ("");
   document.getElementById('cidade').value = ("");
   document.getElementById('estado').value = ("");
}

function meu_callback(conteudo) {
   if (!("erro" in conteudo)) {
      document.getElementById('endereco').value = (conteudo.logradouro);
      document.getElementById('bairro').value = (conteudo.bairro);
      document.getElementById('cidade').value = (conteudo.localidade);
      document.getElementById('estado').value = (conteudo.uf)
   }
    else {
       limpa_formulário_cep();
       alert("CEP não encontrado.");
   }
}

 function pesquisacep(valor) {

 var cep = valor.replace(/\D/g, '');

 if (cep != "") {
    var validacep = /^[0-9]{8}$/;
    if (validacep.test(cep)) {
        document.getElementById('endereco').value = "...";
        document.getElementById('bairro').value = "...";
        document.getElementById('cidade').value = "...";
        document.getElementById('estado').value = "...";

        var script = document.createElement('script');
        script.src = 'https://viacep.com.br/ws/' + cep + '/json/?callback=meu_callback';
        document.body.appendChild(script);
    } 
    else {
        limpa_formulário_cep();
        alert("Formato de CEP inválido.");
    }
} 
   else {
      limpa_formulário_cep();
   }
 };

Form what queries and receives the return of the JS:

  <input name="cep" id="cep"  onblur="pesquisacep(this.value);" ng-model="contribuinte.cep" type="text"/>
  <input name="estado" id="estado"  ng-model="contribuinte.estado" charcase="uppercase" type="text"/>
  <input name="cidade" id="cidade" ng-model="contribuinte.cidade" type="text"/>
  • From what I understand you are using Angularjs along with pure Javascript, correct?

  • Yeah, @Camilosilva . Version 1x.

  • Yes, my controller receives this 'contributor' object'.

  • I honestly did not understand the problem, I found the statement confused.

  • Excuse the sincerity, but I recommend adjusting this Portuguese there, at least for me the question remains meaningless. You said, "On it I fill out some inputs from my form. As an example, returned "Rio de Janeiro" and filled my form the input label 'City'". It means it returns something to you before you type???

  • Has any response helped solve the problem and can address similar questions from other users? If so, make sure to mark the answer as accepted. To do this just click on the left side of it (below the indicator of up and down votes).

Show 1 more comment

3 answers

4


Evaluating the code posted seems to me that you are making misuse or subusing Angularjs, thus losing the advantages of the framework. Example of this is in the code below where you use the model.

   document.getElementById('endereco').value = ("");

As well as several current frameworks Angularjs works internally with the idea of life cycle, which makes it necessary to follow the philosophy adopted by it. Below is an example of how to consume the api you want in the standard adopted by the framework:

angular.module('app', [])
  .controller('CepController', function($http) {
    var vm = this;

    vm.pesquisarCep = function() {

      var cepValido = /^[0-9]{5}[-]?[0-9]{3}$/.test(vm.cep);

      if (cepValido) {

        $http.get("https://viacep.com.br/ws/" + vm.cep + "/json/").then(
          function(response) {
            vm.endereco = response.data;
          },
          function(error) {
            if (error.status === 404) {
              alert('Cep não encontrado');
            }
          } //callback para tratameno de falhas
        );
      } else {
        alert('CEP inválido!');
      }
    }
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<h2>Via Cep</h2>

<form ng-app="app" ng-controller="CepController as vm">
  <input type="text" ng-model="vm.cep" />
  <button ng-click="vm.pesquisarCep()">Pesquisar</button>
  <hr>
  <table border>
    <tr style="background-color:aquamarine">
      <th>CEP</th>
      <th>Logradouro</th>
      <th>Complemento</th>
      <th>Bairro</th>
      <th>Localidade</th>
      <th>UF</th>
      <th>Unidade</th>
      <th>IBGE</th>
      <th>GIA</th>
    </tr>
    <tr ng-if="vm.endereco">
      <td>{{vm.endereco.cep}}</td>
      <td>{{vm.endereco.logradouro}}</td>
      <td>{{vm.endereco.complemento}}</td>
      <td>{{vm.endereco.bairro}}</td>
      <td>{{vm.endereco.localidade}}</td>
      <td>{{vm.endereco.uf}}</td>
      <td>{{vm.endereco.unidade}}</td>
      <td>{{vm.endereco.ibge}}</td>
      <td>{{vm.endereco.gia}}</td>
    </tr>
  </table>
</form>

Plunker: http://plnkr.co/edit/devL9yp3GwZK0Ao2u8nI?p=preview

0

If you will use AngularJS, use it in its entirety. Avoid mixing. The call with jsonp can be checked as below:

(function() {
  angular
    .module('appCep', [])
    .controller('CepController', CepController);

  CepController.$inject = ['$http'];

  function CepController($http) {
    const FORMATO = /^[0-9]{8}$/;
    var vm = this;
    vm.pesquisar = _pesquisar;

    _inicializar();

    function _inicializar() {
      vm.contribuinte = {};
      vm.mensagem = {};
      vm.mensagem.visivel = false;
      _limpar();
    }

    function _pesquisar() {
      var cep = vm.contribuinte.cep.replace(/\D/g, '');

      if (FORMATO.test(cep)) {
        $http.jsonp('https://viacep.com.br/ws/' + cep + '/json/?callback=JSON_CALLBACK').success(_atribuir);
      } else {
        _limpar();
        vm.mensagem.visivel = true;
      }
    }

    function _atribuir(dados) {
      if (dados.erro) {
        _limpar();
        vm.mensagem.visivel = true;
      } else {
        vm.contribuinte.logradouro = dados.logradouro;
        vm.contribuinte.bairro = dados.bairro;
        vm.contribuinte.estado = dados.uf;
        vm.contribuinte.cidade = dados.localidade;

        vm.mensagem.visivel = false;
      }
    }

    function _limpar() {
      vm.contribuinte.logradouro = '...';
      vm.contribuinte.bairro = '...';
      vm.contribuinte.estado = '...';
      vm.contribuinte.cidade = '...';
    }
  };
})();
div.vermelho {
  color: red;
}

label {
  display: inline-block;
  width: 140px;
  text-align: right;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="appCep">
  <div ng-controller="CepController as vm">
    <label>CEP:</label> <input name="cep" id="cep" ng-blur="vm.pesquisar()" ng-model="vm.contribuinte.cep" type="text" />
    <br>
    <label>Logradouro:</label> <input name="logradouro" id="logradouro" ng-model="vm.contribuinte.logradouro" charcase="uppercase" type="text" ng-disabled="true" />
    <br>
    <label>UF:</label> <input name="estado" id="estado" ng-model="vm.contribuinte.estado" charcase="uppercase" type="text" ng-disabled="true" />
    <br>
    <label>Bairro:</label> <input name="bairro" id="bairro" ng-model="vm.contribuinte.bairro" type="text" ng-disabled="true" />
    <br>
    <label>Cidade:</label> <input name="cidade" id="cidade" ng-model="vm.contribuinte.cidade" type="text" ng-disabled="true" />

    <div ng-show="vm.mensagem.visivel" class="vermelho">
      CEP ({{vm.contribuinte.cep}}) não encontrado!
    </div>
  </div>
</div>

In the example above I created the Controller CepController where variables and functions are grouped. The function pesquisar uses the service $http to call the URL and treat the return. Note that I have not manipulated the DOM directly at no point, thus utilizing the full potential of the framework.

-1

First check the line

script.src = 'https://viacep.com.br/ws/' + cep + '/json/?callback=meu_callback';

is building the URL correctly. After, I think it’s worth using the Angular properties to link the HTML elements with your script.

document.getElementById('endereco').value = "...";
document.getElementById('bairro').value = "...";
document.getElementById('cidade').value = "...";
document.getElementById('estado').value = "...";

They should be replaced by

$scope.contribuinte.endereco = (conteudo.logradouro);
$scope.contribuinte.bairro = (conteudo.bairro);
$scope.contribuinte.cidade = (conteudo.localidade);
$scope.contribuinte.estado = (conteudo.uf);
  • You’ve noticed that you’re mixing angular syntax into a native Java file?

  • Yes, this is possible as long as this code is inside your Controller

Browser other questions tagged

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