Take PHP variable and display in input

Asked

Viewed 1,704 times

4

Good afternoon, folks. I am wanting to take the value of the Cpf variable, after it is treated, and display it inside an input.

practicing.php

    <fieldset style="width:50%; margin: 0px auto; ">
        <legend>Colocando PONTO no CPF</legend>
        <form method="POST" action="validaPraticando.php">
            <label for="cpf">CPF</label>
            <input type="number" name="cpf" placeholder="Sem pontos e traço" required />
            <input type="submit" value="ENVIAR" name="button"/><br/><br/>
            <input name='recebe' value="QUERO_EXIBI-LA_AQUI" readonly style='width:100%;'/>
        </form>
    </fieldset>

validationPraticando.php

<?php
$cpf = $_POST['cpf'];
$campoRecebe = $_POST['recebe'];

if(strlen($cpf) == 11){
    $pegaCpf = substr($cpf,0,3).'.'.substr($cpf,3,3).'.'.substr($cpf,6,3).'-'.substr($cpf,9,2);
    echo $pegaCpf;
}else{
    echo "CPF inválido";
}
  ?>
  • Has knowledge about asynchronous requests (AJAX)?

  • Don’t have. Can you give a brief explanation? Then I do a research on the subject.

  • Are you aware of Jquery ?

  • I do not have Rickpariz. I will give a researched on the subject.

  • I’ll give you an answer usingjquery and ajax, I’ll try to be very simple and explain it to you

  • @Guilhermewayne, if my answer helps you, and it’s right, don’t forget to mark it as the solution, so that other members of the community know that this question is closed.

Show 1 more comment

2 answers

3


This is a very simple thing to do, using asynchronous requests (ajax), well come on..

Ajax is the use of the Xmlhttprequest object to communicate with server-side scripts. What makes the ajax a great tool, are your asynchronous requests, which means that it can do all this without the need to refresh the page.

This is the juxtaposition you want, the form will be sent, and the Cpf value will appear in a input after its validation. This without updating the page, not to occur loss of data and etc.

You can read more about ajax here

To use ajax, it is very common for people to use a library javascript calling for jquery. It is a library that we as web developers have an obligation to know, it makes our life much easier.

You can read more about jquery here.

Well let’s go to the code !

NOTE: Don’t forget to import jquery at the bottom of the page !

The Html

<fieldset style="width:50%; margin: 0px auto; ">
        <legend>Colocando PONTO no CPF</legend>
        <form id="form">
            <label for="cpf">CPF</label>
            <input type="number" name="cpf" placeholder="Sem pontos e traço" required />
            <input type="submit" value="ENVIAR" name="button"/><br/><br/>
            <input name='recebe' id="recebe" value="QUERO_EXIBI-LA_AQUI" readonly style='width:100%;'/>
        </form>
    </fieldset>

There is no need to put attrs as action and method in tag form, since we will use ajax. If you notice I put one id form and also in the input which will receive the formatted Cpf, this was done so that we can find the input correct when placing the value with jquery

Javascript

let’s start with Function ready of jquery, it says the following: "After the document (page) is loaded, run this function..

Syntax

$(document).ready(function(){
  // tudo que estiver aqui poderá ser executado, após o documento ser carregado
});

Let’s continue..

$(document).ready(function(){
  // tudo que estiver aqui poderá ser executado, após o documento ser carregado

  $("#form").on("submit", function(e){
    // está função diz, que quando esse formulario for enviado, tudo oque estiver aqui será executado.
    e.preventDefault(); // está função é usada pro form não ir para outra pagina, pois o evento padrão de um formulario é ir para outra pagina.
    var data = $("#form").serialize(); // a function serialize serve para pegar todos os valores que foram colocados nos inputs do form
    $.ajax({
      // está é a função ajax, do jquery, ela será usada para fazer a requisição assícrona.
      url: "validaPraticando.php", // aqui vai a url da requisição, nela é colocado o valor do atributo action da tag form
      data:  data, // aqui vai os dados para o servidor, geralmente é os inputs do form
      method: "POST", // aqui vai o método da requisição, acho que você já sabe sobre o get e post !
      dataType: "json", // aqui será o tipo de resposta que vamos receber, será no formato json, um formato simples e mais usado.
      success: function(data){
        // essa é a function success, ela ira ser executada se a requisição for feita com sucesso
        $("#retorno").val(data); // aqui estamos setando o valor retornado do php, no input
         // a variavel data, veio do parametro da function, e será a resposta do php.
      },
      error: function(){
        // essa é funcion error, ela será executada caso ocorrer algum erro na requisição
        alert("erro na requisição");
      }
    });
  });

});

Finally, the php.. It will be exactly as it is, what will change is the way you will return Cpf.

<?php
$cpf = $_POST['cpf'];

if(strlen($cpf) == 11){
    $pegaCpf = substr($cpf,0,3).'.'.substr($cpf,3,3).'.'.substr($cpf,6,3).'-'.substr($cpf,9,2);
    echo json_encode($pegaCpf);
}else{
    echo json_encode("CPF Invalido");
}
  ?>

To return answers in format json (is the format we set in the request ajax) It is common to use Function json_encode(data).

I hope I helped ! At first, it may seem very confusing these things.. jquery, ajax, json and etc.. but you will see that it is very simple and easy to learn.

  • Thanks even Rickpariz, helped a lot. I will study a lot on the subject. Thanks for the tip.

2

The above answer is very good and will work perfectly. If your idea is something simpler, because from what I understand you are starting your studies, you can put all the data on one page

practicing.php :

<?php

        if (isset($_POST['cpf'])) {
            $cpf = $_POST['cpf'];

            if(strlen($cpf) == 11){
                $pegaCpf = substr($cpf,0,3).'.'.substr($cpf,3,3).'.'.substr($cpf,6,3).'-'.substr($cpf,9,2);

            }else{
                echo "CPF inválido";
            }
        }

  ?>


<fieldset style="width:50%; margin: 0px auto; ">
    <legend>Colocando PONTO no CPF</legend>
    <form method="POST" action="praticando.php">
        <label for="cpf">CPF</label>
        <input type="number" name="cpf" placeholder="Sem pontos e traço" required />
        <input type="submit" value="ENVIAR" name="button"/><br/><br/>
          <?php
            if (isset($_POST['cpf'])) {
            echo"<input name='recebe' value='" + $pegaCpf + "' readonly style='width:100%;'/>"
            }
            else{
                echo"<input name='recebe' value='CPF inválido' readonly style='width:100%;'/>"
            }
          ?>
    </form>
</fieldset>

But remembering that this only works for your studies.

  • Thanks Luiz Santos, thanks for the tip.

Browser other questions tagged

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