Post php only with all fields filled out

0

My form is always being sent, even if there is nothing in the input, can someone give me a light?

HTML:

<form id="ajax" method="post">
     <div class="form-group">
         <input type="text" name="name" class="form-control required" placeholder="Nome">
     </div>
     <div class="form-group">
          <input type="email" name="email" class="form-control required" placeholder="E-mail">
     </div>
     <div class="form-group">
          <input type="text" name="phone" class="form-control required" placeholder="Telefone (com DDD)">
     </div>
     <div class="form-group">
          <input type="text" id="autocomplete"  name="city" class="form-control required" placeholder="Cidade"/>
     </div>
     <div class="form-group">
          <input type="text" class="form-control required" name="zip_code" placeholder="Compra, construção, quitar financiamento?">
     </div>
     <input type="submit" class="btn btn-default quote_btn" value="Solicitar proposta">
</form>

JS:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script><scripttype="text/javascript">
$(document).ready(function(){
    $('#ajax').submit(function(){
        var dados = $( this ).serialize();

        $.ajax({
            type: "POST",
            url: "lead.php",
            data: dados,
            success: function( data )
            {
                alert('Enviado com sucesso');
            }
        });

        return false;            
    });
});
</script>
    
asked by anonymous 29.05.2018 / 22:38

2 answers

1

You can use the jQuery Validate plugin that validates the entire form before requesting Ajax. You can even create rules and messages for each field. Very simple and easy to use. Load the script on the page:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>

AndthescriptwiththevalidatorandAjaxtogether:

$(document).ready(function(){

   $('#ajax').validate({  
    
      //regras e mensagens para os campos
      rules: {  
          name: { required: true, minlength: 2 },  
          email: { required: true, email: true },  
          phone: { required: true },
          city: { required: true },
          zip_code: { required: true }
      },  
      messages: {  
          name: { required: 'Informe o nome', minlength: 'Mínimo 2 letras' },  
          email: { required: 'Informe o seu email', email: 'Informe um email válido' },  
          phone: { required: 'Informe o telefone' },
          city: { required: 'Informe a cidade' },
          zip_code: { required: 'Informe o CEP' }
   
      },
      
      submitHandler: function(form){

           var dados = $(form).serialize();
           alert("Formulário OK!"); // apenas exemplo, pode apagar esta linha
    
           $.ajax({
               type: "POST",
               url: "conecta.php",
               data: dados,
               success: function( data )
               {
                   alert('Enviado com sucesso');
               }
           });
   
           return false;            
      }
   });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scriptsrc="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script><formid="ajax" method="post">
     <div class="form-group">
         <input type="text" name="name" class="form-control required" placeholder="Nome">
     </div>
     <div class="form-group">
          <input type="email" name="email" class="form-control required" placeholder="E-mail">
     </div>
     <div class="form-group">
          <input type="text" name="phone" class="form-control required" placeholder="Telefone (com DDD)">
     </div>
     <div class="form-group">
          <input type="text" id="autocomplete"  name="city" class="form-control required" placeholder="Cidade"/>
     </div>
     <div class="form-group">
          <input type="text" class="form-control required" name="zip_code" placeholder="Compra, construção, quitar financiamento?">
     </div>
     <input type="submit" class="btn btn-default quote_btn" value="Solicitar proposta">
</form>
    
29.05.2018 / 22:59
1

Using HTML5

The simple solution to this problem, without using JS is to use only the required attribute of HTML5 itself in the input fields. Therefore, the user's own browser will not let the form be sent if it is not complete.

So the code looks like this:

<form id="ajax" method="post">
    <div class="form-group">
        <input type="text" name="name" class="form-control required" placeholder="Nome" required >
    </div>
    <div class="form-group">
        <input type="email" name="email" class="form-control required" placeholder="E-mail" required >
    </div>
    <div class="form-group">
        <input type="text" name="phone" class="form-control required" placeholder="Telefone (com DDD)" required >
    </div>
    <div class="form-group">
        <input type="text" id="autocomplete" name="city" class="form-control required" placeholder="Cidade" required />
    </div>
    <div class="form-group">
        <input type="text" class="form-control required" name="zip_code" placeholder="Compra, construção, quitar financiamento?" required >
    </div>
    <input type="submit" class="btn btn-default quote_btn" value="Solicitar proposta">
</form>

Using jQuery

If you still want to use jQuery, you can use a loop in the elements of the form and check that they are valid, like this:

<script type="text/javascript">
$(document).ready(function () {
    $('#ajax').submit(function () {
        // Validação dos dados
        var valid = true;
        $.each($("#ajax input"), function (i, value) {
            if (!$(value).val()) {
                valid = false;
            }
        });

        if (!valid) {
            alert("Forumlário inválido");
            return false;
        }

        // Código do ajax mantido
        var dados = $(this).serialize();

        $.ajax({
            type: "POST",
            url: "lead.php",
            data: dados,
            success: function (data) {
                alert('Enviado com sucesso');
            }
        });

        return false;
    });
});

    
29.05.2018 / 22:48