Send html form with ajax to process form data with php and return to index.html

Asked

Viewed 48 times

-1

I have a form in html that receives a zip code, and is sent (action) to my class in PHP, which returns the address and I wanted to take this return address and put in my html page, but I don’t know how to do it with javascript.

html:

<header class="header">
        Cabeçalho! Faça suas pesquisas aqui!
</header>

<article class="busca">
     <form class="form" method="POST" action="ControllerTeste.php">
          CEP: <input class ="cep" type="text" name="cep" placeholder="Insira o cep" required/>
          <input class="submit" type="submit" value="Buscar"/>
     </form>
</article>

<article class="data">
        <!--Dados PHP via JS-->
</article>

PHP:

<?php
Class Controller{
    public $cep;

    public function ConsultaViaCEP(){
        $cep = Controller::setFormCEP();
        $cep = preg_replace("/[^0-9]/", "", $cep);
        $url = file_get_contents("http://viacep.com.br/ws/$cep/json/");
        $json = json_decode($url, true);
        return $json;
    }
    [...getters and setters]
    private function setFormCEP(){
        $formCEP = $_POST['cep'];
        return $formCEP;
    }
}

    echo Controller::getCEP()."<br>";
    echo Controller::getLogradouro()."<br>";
    echo Controller::getComplemento()."<br>";
    echo Controller::getBairro()."<br>";
    echo Controller::getLocalidade()."<br>";
    echo Controller::getUF()."<br>";
?>

1 answer

0

Do you need this PHP? As you can process this request directly through javascript, see this example code from VIACEP itself

<html>
<head>
<title>ViaCEP Webservice</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<!-- Adicionando JQuery -->
<script src="https://code.jquery.com/jquery-3.4.1.min.js"
        integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
        crossorigin="anonymous"></script>

<!-- Adicionando Javascript -->
<script type="text/javascript" >

    $(document).ready(function() {

        function limpa_formulário_cep() {
            // Limpa valores do formulário de cep.
            $("#rua").val("");
            $("#bairro").val("");
            $("#cidade").val("");
            $("#uf").val("");
            $("#ibge").val("");
        }

        //Quando o campo cep perde o foco.
        $("#cep").blur(function() {

            //Nova variável "cep" somente com dígitos.
            var cep = $(this).val().replace(/\D/g, '');

            //Verifica se campo cep possui valor informado.
            if (cep != "") {

                //Expressão regular para validar o CEP.
                var validacep = /^[0-9]{8}$/;

                //Valida o formato do CEP.
                if(validacep.test(cep)) {

                    //Preenche os campos com "..." enquanto consulta webservice.
                    $("#rua").val("...");
                    $("#bairro").val("...");
                    $("#cidade").val("...");
                    $("#uf").val("...");
                    $("#ibge").val("...");

                    //Consulta o webservice viacep.com.br/
                    $.getJSON("https://viacep.com.br/ws/"+ cep +"/json/?callback=?", function(dados) {

                        if (!("erro" in dados)) {
                            //Atualiza os campos com os valores da consulta.
                            $("#rua").val(dados.logradouro);
                            $("#bairro").val(dados.bairro);
                            $("#cidade").val(dados.localidade);
                            $("#uf").val(dados.uf);
                            $("#ibge").val(dados.ibge);
                        } //end if.
                        else {
                            //CEP pesquisado não foi encontrado.
                            limpa_formulário_cep();
                            alert("CEP não encontrado.");
                        }
                    });
                } //end if.
                else {
                    //cep é inválido.
                    limpa_formulário_cep();
                    alert("Formato de CEP inválido.");
                }
            } //end if.
            else {
                //cep sem valor, limpa formulário.
                limpa_formulário_cep();
            }
        });
    });

</script>
</head>

<body>
<!-- Inicio do formulario -->
  <form method="get" action=".">
    <label>Cep:
    <input name="cep" type="text" id="cep" value="" size="10" maxlength="9" /></label><br />
    <label>Rua:
    <input name="rua" type="text" id="rua" size="60" /></label><br />
    <label>Bairro:
    <input name="bairro" type="text" id="bairro" size="40" /></label><br />
    <label>Cidade:
    <input name="cidade" type="text" id="cidade" size="40" /></label><br />
    <label>Estado:
    <input name="uf" type="text" id="uf" size="2" /></label><br />
    <label>IBGE:
    <input name="ibge" type="text" id="ibge" size="8" /></label><br />
  </form>
</body>

</html>
  • It was for studies, but it was already solved. I was already aware of this, but I can really do it directly by javascript

  • By the way, how can I delete my questions?

Browser other questions tagged

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