Post php only with all fields filled

Asked

Viewed 247 times

0

My form is always being sent, even if there is nothing in the input, someone can 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>
<script type="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>

2 answers

1

Using HTML5

The most solution simple for this problem, without using JS is to use only the attribute required HTML5 itself in the input fields. Thus, the user’s own browser nay let the form be sent if it is not complete.

So the code goes 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 form elements and check that they are valid, so:

<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;
    });
});

1


You can use the plugin jQuery Validate which validates the entire form before ordering Ajax. You can even create rules and messages for each field. Very simple and easy to use. Load the script into the tab:

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

And the script with the validator and Ajax together:

$(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>
<script src="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>
<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>

Browser other questions tagged

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