Values are going empty in JQuery

2

I have a form, of which I am trying to get the values this way, but it is not working. Where am I going wrong?

JQuery

<script type="text/javascript">
   $(document).ready(function(){
   data = $('#login-form').serialize();

  $.post("validar.php", {
     d: data,
   },
  function (d) {
     console.log(data);
      $('#myModal').modal('show');
   });
    return false;
 });
</script>

Console result:

  

TypeAccess = Select & LoginAccess = & AccessPassword =

Form

<form method="post" id="login-form">
<ul>
<li>
 <label>Tipo de Acesso:</label>
 <select id="tipoAcesso" class="form-control" name="TipoAcesso" onChange="alterar(this.value);">
    <option value="Selecione">Selecione</option>
  <option value="Aluno">Aluno</option>
    <option value="Responsável">Responsável</option>
    <option value="Professor">Professor</option>
  <option value="Coordenador">Coordenador</option>
  <option value="Secretaria">Secretaria</option>
  <option value="Adm. Escola">Adm. Escola</option>
</select>
</li>
<li>
 <label  id="texto">Login:</label>
 <input required="required" type="text" name="LoginAcesso" id="username" placeholder="Matrícula" class="form-control" />
</li>
<li>
 <label>Senha:</label>
 <input required="required" type="password" name="SenhaAcesso" id="password" placeholder="Senha" class="form-control" />
 <button type="button" id="show_password" name="show_password" class="fa fa-eye-slash" aria-hidden="true"></button>
</li>
<li class="text-right">
 <button type="submit" name="submit" class="btn btn-primary">Acessar</button>
</li>
</ul>
</form>
    
asked by anonymous 05.07.2017 / 15:14

1 answer

2
<script type="text/javascript">
       $(document).ready(function(){
           $('#login-form').submit(function() {

                data = $('#login-form').serialize();

                $.post("validar.php", {
                d: data,
                },
                function (d) {
                console.log(data);
                $('#myModal').modal('show');
                });

                return false;

           }); });
    </script>

Put it this way and it should work.

The error

The .ready() function of jquery is saying that the code will only be executed once there is security for manipulating the document. Learn More

And this happens soon after the page loads.

What was happening is that soon after the page was loaded the variable data already received the values of the fields of form login-form . As all fields are empty when the page loads the result would always be:

  

TypeAccess = Select & LoginAccess = & AccessPassword =

The fix

Using the .submit() function you are telling the code that the variable data will only receive the values of the form login-form after the type='submit' button is clicked. With all the validations made for the fields. The return for the variable data should already be satisfactory.

More about function .submit() (link in English)

    
05.07.2017 / 15:21