Check Availability of CEP

Asked

Viewed 1,626 times

2

I’m trying to develop but I’m not very familiar with programming with Ajax, jQuery and Javascript, then I would like help I have a field that takes the ZIP CODE of the customer and a button so that when they click the return button if that ZIP CODE this covered there for delivery, if it is not showing that we do not deliver in that region but all without leaving the page that I am all on the same page.

  • Recently I was just writing a Javascript for research of Ceps, using some Apis available, what have you tried ? Would like edit your question and put the code ?

  • type by which I understood that the guy who is a script that the user will type a cep and if the cep is not equal to any of the array it will return that is not available for delivery.

  • that my namesake said, I have tried to see api’s but the delivery scheme is not by the post office so there is no way to use the delivery system api and own

  • Yes, that I understood, see how you want to check the region covered ? by State, Cities ?

  • covering cities of specific ceps.

  • 1

    @Double personality Túliogomes ?? :D

Show 1 more comment

3 answers

2

You have stored the available Zip Codes for delivery, right?

Just make an ajax call on the following template:

            $.ajax({
                type: 'GET', //ou POST
                url: 'nome_da_pagina.php',
                data: {cep: $('#cep').val()},
                dataType: 'json',
                success: function(data){
                    //retorno uma variável booleana chamada success no json
                    if (data.success){
                        //sucesso: o cep verificado está disponível para entrega
                    }else{
                        //o cep verificado não está disponível
                    }
                },
                error: function(xhr){
                    //tratar o erro na chamada ajax
                }
            });

In the example the tag input has the id cep, and the PHP script will receive the variable as well as the cep. You can receive the value with the following line:

$cep = isset($_GET['cep']) ? $_GET['cep'] : '';

Inside PHP you will make a query to the database that will verify if the value of the variable exists in the table.

I hope I’ve helped!

  • i wanted Ajax to already do this check and not php

  • This list of possible Zip for delivery is where? database? txt? the language Voce uses, what is it? there are thousands of very simple resolutions in the stack itself.

  • had thought of an array. I didn’t find anything of the kind I’m wanting here @Michelsimões

2


Here are some examples of how to check ZIP CODE for Cities, to use just create an object with the first five digits of the range Ceps, example:

The city of Campinas which is in the state of São Paulo the Ceps begin with 13000 and goes up to 13139.

jQuery and PHP

Filing cabinet query CEP.php

$getCEP = filter_input(INPUT_GET, 'cep');
// A variável $Abranage pode ser o retorno de consulta
$Abrange = [
    // CAMPINAS
    [
        'inicio' => 13000,
        'fim' => 13139,
        'cidade' => 'Campinas'
    ],
    // PAULINIA
    [
        'inicio' => 13140,
        'fim' => 13140,
        'cidade' => 'Paulinia'
    ],
    // COSMOPOLIS
    [
        'inicio' => 13150,
        'fim' => 13150,
        'cidade' => 'Cosmopolis'
    ]
];
// Pega os cinco primeiros digitos do CEP informado pelo usuário
$CincoPrimeirosDigitos = substr($getCEP, 0,5);
$Check = false;
foreach($Abrange as $cidade) {
  // Verifica se é igual ou se esta entre INICIO e FIM
  if ($CincoPrimeirosDigitos >= $cidade['inicio'] && $CincoPrimeirosDigitos <= $cidade['fim']) {
    $Check = true;
  }
}
if ($Check) {
  echo json_encode(true);
} else {
  echo json_encode(false);
}

HTML

<div class="alert success">Entregamos em sua região</div>
<div class="alert info">Lamentamos, não entregamos em sua região!</div>
<input type="text" name="cep" id="cep" placeholder="Informe um CEP" />
<input type="button" id="VerificarCEP" value="Verificar" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$("#VerificarCEP").on('click', function(e) {
  var campo = $('#cep');
  var check = false;
  // Verifica a quantidade de digitos
  if (campo.val().length < 8) return;
  var url = 'consultaCEP.php?cep=${cep}'.replace('${cep}', campo.val());

  $.getJSON(url, function (retorno) {
      console.log(retorno);
    if (retorno) {
        $(".success").show();
        $(".info").hide();
    } else {
        $(".success").hide();
        $(".info").show();
    }
  });
});
</script>

In the two examples below I am using the API of the site Viacep to carry out the consultation.

jQuery

// Por Cidade
// Coloque somente os 5 primeiros digitos, exe:
// Campinas os CEPs tem a númeração començando por
// 13000 e vai até 13139
const abrange = [
  // CAMPINAS
  {
    inicio: 13000,
    fim: 13139,
    cidade: 'Campinas'
  },
  // PAULINIA
  {
    inicio: 13140,
    fim: 13140,
    cidade: 'Paulinia'
  },
  // COSMOPOLIS
  {
    inicio: 13150,
    fim: 13150,
    cidade: 'Cosmopolis'
  }
];

$("#VerificarCEP").on('click', function(e) {
  var campo = $('#cep');
  var check = false;
  // Verifica a quantidade de digitos
  if (campo.val().length < 8) return;
  var url = 'https://viacep.com.br/ws/${cep}/json/'.replace('${cep}', campo.val());
  
  $.getJSON(url, function (retorno) {
    if (retorno.erro) {
      $(".success, .info").hide();
      $(".erro").show();
    } else {
      var ini = retorno.cep.substring(0, 5);
      var t = $.grep(abrange, function(cep, i){
        if(ini >= cep.inicio && ini <= cep.fim) {
          check = true;
        }
      });
      
      if (check) {
        $(".erro, .info").hide();
        $(".success").show();
      } else {
        $(".erro, .success").hide();
        $(".info").show();
      }
    }
  });
});
.alert {
  padding: 20px;
  color: white;
  margin-bottom: 15px;
  display: none;
}
.erro {
  background-color: #f44336;
}
.success {
  background-color: green;
}
.info {
  background-color: #069;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="alert success">Entregamos em sua região</div>
<div class="alert erro">CEP Inválido</div>
<div class="alert info">Lamentamos, não entregamos em sua região!</div>
<input type="text" name="cep" id="cep" placeholder="Informe um CEP" />
<input type="button" id="VerificarCEP" value="Verificar" />

SE6

// Por Cidade
// Coloque somente os 5 primeiros digitos, exe:
// Campinas os CEPs tem a númeração començando por
// 13000 e vai até 13139
const abrange = [
  // CAMPINAS
  {
    inicio: 13000,
    fim: 13139,
    cidade: 'Campinas'
  },
    // PAULINIA
  {
    inicio: 13140,
    fim: 13140,
    cidade: 'Paulinia'
  },
  // COSMOPOLIS
  {
    inicio: 13150,
    fim: 13150,
    cidade: 'Cosmopolis'
  }
  // Basta adicionar mais cidades, ou retornar através de dados cadastrados no banco de dados.
];
const buscarCEP = (cep) => {
  let check = false;
  if (cep.length < 8) return;
  let url = 'https://viacep.com.br/ws/${cep}/json/'.replace('${cep}', cep);
  fetch(url)
    .then((res) => {
    if (res.ok) {
      res.json().then((json) => {
        if (json.erro) {
            document.querySelector('.success').style.display = 'none'; 
            document.querySelector('.info').style.display = 'none';
            document.querySelector('.erro').style.display = 'block';
        } else {
          abrange.forEach((e) => {
            // Pega os 5 primeiros digitos
            let ini = json.cep.substring(0, 5);
            // Verifica o intervalo
            if (ini >= e.inicio && ini <= e.fim) {
              console.log('Abrange');
              check = true;
            }
          });
      
          if (check) {
            document.querySelector('.success').style.display = 'block';
            document.querySelector('.info').style.display = 'none';
            document.querySelector('.erro').style.display = 'none';
          } else {
            document.querySelector('.success').style.display = 'none';
            document.querySelector('.info').style.display = 'block';
            document.querySelector('.erro').style.display = 'none';
          }
        }
      });
    }
  });
}

let btnVerificarCEP = document.querySelector('#VerificarCEP');
// Adiciona o evento click
btnVerificarCEP.addEventListener('click', function(e) {
  let campoCEP = document.querySelector('#cep');
  buscarCEP(campoCEP.value);
});
.alert {
  padding: 20px;
  color: white;
  margin-bottom: 15px;
  display: none;
}
.erro {
  background-color: #f44336;
}
.success {
  background-color: green;
}
.info {
  background-color: #069;
}
<div class="alert success">Entregamos em sua região</div>
<div class="alert erro">CEP Inválido</div>
<div class="alert info">Lamentamos, não entregamos em sua região!</div>
<input type="text" name="cep" id="cep" placeholder="Informe um CEP" />
<input type="button" id="VerificarCEP" value="Verificar" />

  • The person who has denied, please give an explanation of what is wrong ? So what can I be corrected for!

  • what the difference between one code and another can explain?

  • Both do the same, the difference is that the jQuery is a function library and to use these functions you need to import the jQuery, to learn about Ecmascript read this one reply here in the Sopt.

  • I am with basically the same problem I tested its function here it is certain only that the fields Divis We deliver in your region and the others are not hidden

  • @Tulip tree you’re doing the first that’s just the PHP with jQuery ?

  • I already understood why kkk did not put the style

  • 1

    @Tuliovieira this happens rsrs, if the answer has helped solve your problem / doubt, consider mark as accepted / useful.

  • I own the post not kkk

Show 3 more comments

1

I won’t go into explaining, but basically, there’s an array with the fruits, "Banana", "Orange", "Apple", "Mango" if you type one of them in the field it gives you the answer that there is, if not, there isn’t, I even put ifs to manipulate your response. hug and good luck!

function myFunction() {
    variavel = document.getElementById("campo").value;
    var fruits = ["Banana", "Laranja", "Maçã", "Manga"];
    var a = fruits.indexOf(variavel);
if(a >= 0){
   retorno = "Há a variável";
} else {
   retorno = "nao há a variavel";
}
    document.getElementById("demo").innerHTML = retorno;
}
<input type="text" id="campo" name="campo" >
<button onclick=" myFunction()">verificar</button>
<div id="demo"></div>

  • Can you imagine the amount of Ceps available ? This would not be a great idea, since he would have to inform ZIP CODE for ZIP CODE to be able to check.

  • why I asked before the user how HE thinks to do this, before suggesting something absurd...

Browser other questions tagged

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