How to send data via form to php file and return the result in an html field

Asked

Viewed 383 times

-1

I wanted to send the data via form, which would be used in my php class, and with javascript capture this result and play in my html field, with on click of js. But I’m not succeeding with "action" because it requests another page, in case my .php. file and I don’t get the return in my html file. What’s the best way to solve this?

I have the following form:

<form  class="form" method="GET">
     CEP: <input type="text" name="cep" placeholder="Insira o cep" required/>
     <input class="submit" type="submit" value="Buscar"/>
</form>

And a field to receive data in php:

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

In the file . js:

$(document).ready(function(){
     $(document).on('click', '.submit', function(){
          $.post('testephp.php', function(retorna){
          $(".data").html(retorna);
          });
     });
});

Php class:

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]

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

inserir a descrição da imagem aqui

1 answer

0

If the question is as I understand it, you can use preventDefault to prevent the page from being submitted and run only on JS.

$(document).on('click', '.submit', function( e ){
     e.preventDefault();

     $.post('testephp.php', function(retorna){
          $(".data").html(retorna);
     });
});
  • the action of the form, sends the data of the html form, sending and redirecting to the php file, however, I wanted to receive the data of the html form, that php processed this data and sent the result to the field in html intended for this, ie the part in "yellow"

  • Maybe getting the html form data by js and the javascript itself sent to my php file would solve this problem, since it has no page load. But you have a lot of problems doing that, first I know not to say if it would be right and also, I don’t know how it would be done

Browser other questions tagged

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