JavaScript message is not appearing in the input

1

Good morning. I want to cause the result of the cpf variable to be displayed in the input 'receive'.

practicando.php

<head>
    <meta charset="UTF-8"/>
    <script type="text/javascript" src="pratica.js"></script>
</head>
<body>
    <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" readonly style='width:100%;'/>
        </form>
    </fieldset>
</body>

validaPraticando.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");
}

pratica.js

$(documento.ready(function(){
$("#form").on("submit",function(e){

    e.preventDefault();
    var data = $("#form").serialize();
    $.ajax({
        url: "validaPraticando.php",
        data: data,
        method: "POST",
        dataType: "json",
        success: function(data){
            $("#retorno").val(data);
        },
        error: function(){
            alert("erro na requisição");
        }
    });
  });
});
    
asked by anonymous 11.09.2017 / 14:40

2 answers

0

You are assigning the value to an element that does not exist retorno . Make sure the page returns the desired information and corrects the field where it will be assigned.

Change from

success: function(data){
   $("#retorno").val(data);
},

To:

success: function(data){
       //console.log() ou alert() apenas para verificar o que retornou.
       console.log(data); 
       $("#recebe").val(data);
    },
    
11.09.2017 / 14:59
0

If you want to use the cpf mask, use this example, along with my tip underneath and typing, you will do everything automatically:

Masks with jQuery: Phone, CPF and CNPJ

But if you just want to validate the amount of characters, just use one minlength="11" and maxlength='14' within your input getting:

<input type="number" name="cpf" minlength="11" 'maxlength='14' placeholder="Sem pontos e traço" required />

Finally, if you want to see if cpf is actually valid, you can use a function that is already ready, easy to find on several sites like this:

How to validate script-side client-side CPF ?

or

link

    
11.09.2017 / 14:48