Call a preloader before sending contact

Asked

Viewed 448 times

0

I have the following form and its validations. How would I call a gif (preloader) to the form at the moment the user clicks to submit. It should disappear when the ajax is completed.

function solucoesForm() {

  if ($.trim($('#soluctionsName').val()) == '' || $.trim($('#soluctionsName').val()) == 'Nome') alert('Informe seu nome!');
  else if ($.trim($('#soluctionsEmail').val()) == '' || $.trim($('#soluctionsEmail').val()) == 'E-mail') alert('Informe seu e-mail!');
  else if ($.trim($('#soluctionsPhone').val()) == '' || $.trim($('#soluctionsPhone').val()) == 'Telefone') alert('Informe seu telefone!');
  else if ($.trim($('#soluctionsEmpresa').val()) == '' || $.trim($('#soluctionsEmpresa').val()) == 'Empresa') alert('Informe a Empresa!');
  else if ($.trim($('#soluctionsCidade').val()) == '' || $.trim($('#soluctionsCidade').val()) == 'Cidade') alert('Informe sua Cidade!');
  else {
    $.post('carregamentos/solucoes.php',
      $('#solucoesFormulario').serialize(),
      function(abc) {
        alert('Mensagem enviada com sucesso!');
      }
    );
  }
  return false;
}
<form class="contact soluctionsForm margin-top-190 margin-bottom-110" id="solucoesFormulario" action="" name="solucoesFormulario" method="post" onsubmit="return solucoesForm();">
  <div class="grid_380 float-left">
    <div class="margin-bottom-30">
      <h2>Solicite um orçamento</h2>
      <h2>para esta solução</h2>
    </div>
    <input type="text" class="margin-bottom-20 grid_380" name="Nome" placeholder="Nome" id="soluctionsName" />
    <input type="text" class="margin-bottom-20 grid_380" name="E-mail" placeholder="E-mail" id="soluctionsEmail" />
    <input type="text" class="margin-bottom-20 grid_380" name="Telefone" placeholder="Telefone" id="soluctionsPhone" />
    <input type="text" class="margin-bottom-20 grid_380" name="Empresa" placeholder="Empresa" id="soluctionsEmpresa" />
    <input type="text" class="grid_380" name="Cidade" placeholder="Cidade" id="soluctionsCidade" />
    <input class="grid_380 margin-top-25" type="submit" name="Enviar" />
  </div>
</form>

3 answers

2

Do you want the code to make the gif appear? I believe this is your responsibility, what you are looking for must be logic. It’s very simple, you want an image to appear when you click to send, and when it’s done, it disappears, right? You can display the image after the validation is completed, before performing the post, so an immediate response is given to the user that something is being done.
After that, you need to wait for the post be completed. In your example you have already shown when it is completed, so it is there that the command should be placed for the image to disappear.

function solucoesForm() {
  if ($.trim($('#soluctionsName').val()) == '' || $.trim($('#soluctionsName').val()) == 'Nome') alert('Informe seu nome!');
  else if ($.trim($('#soluctionsEmail').val()) == '' || $.trim($('#soluctionsEmail').val()) == 'E-mail') alert('Informe seu e-mail!');
  else if ($.trim($('#soluctionsPhone').val()) == '' || $.trim($('#soluctionsPhone').val()) == 'Telefone') alert('Informe seu telefone!');
  else if ($.trim($('#soluctionsEmpresa').val()) == '' || $.trim($('#soluctionsEmpresa').val()) == 'Empresa') alert('Informe a Empresa!');
  else if ($.trim($('#soluctionsCidade').val()) == '' || $.trim($('#soluctionsCidade').val()) == 'Cidade') alert('Informe sua Cidade!');
  else {
    // Fomulário validade, exibe uma mensagem de carregamento
    $.post('carregamentos/solucoes.php',
      $('#solucoesFormulario').serialize(),
      function(abc) {
        // "Mensagem enviada com sucesso", logo, o processo do post acaba aqui, já podemos retirar a imagem.
        alert('Mensagem enviada com sucesso!');
      }
    );
  }
  return false;
}

2


I suggest you use $.ajax in time of $.post, because the first has a method for it. That is, it is more complete. You could use it like this:

$.ajax({
    method: "POST",
    url: "carregamentos/solucoes.php",
    beforeSend: function (xhr) {
        $('#divOndeQueresMostrarPreload').html('preload.gif');
    },
    data: $('#solucoesFormulario').serialize(),
    success: function (abc) {
        // "Mensagem enviada com sucesso", logo, o processo do post acaba aqui, já podemos retirar a imagem.
        alert('Mensagem enviada com sucesso!');
    }
});

Another suggestion to make this validation:

function solucoesForm() {
    var toValidate {
        soluctionsName: 'Nome',
        soluctionsEmail: 'E-mail',
        soluctionsPhone: 'Telefone',
        soluctionsCidade: 'Cidade',
        soluctionsEmpresa: 'Empresa'
    }
    var validated = true;
    Object.keys(toValidate).forEach(function (key) {
        if (!validated) return;
        var val = $.trim(document.getElementById(key).value);
        if (val && val != toValidate[key]) return;
        alert('Por favor complete o campo ' + key);
        validated = false;
    });

    if (validated) $.ajax({
        method: "POST",
        url: "carregamentos/solucoes.php",
        beforeSend: function (xhr) {
            $('#divOndeQueresMostrarPreload').html('preload.gif');
        },
        data: $('#solucoesFormulario').serialize(),
        success: function (abc) {
            // "Mensagem enviada com sucesso", logo, o processo do post acaba aqui, já podemos retirar a imagem.
            alert('Mensagem enviada com sucesso!');
        }
    });
    return false;
}

2

You can create a block in your HTML document containing the content that will be shown at the time of the request. For example:

// foo.css
.imagem-carregando { visibility: hidden }

// foo.html
<img class='imgem-carregando' src='imagem.gif'>

It would then suffice at the time of the request for you to change the rule of that element to visibility:visible.

To do this, you can use the function $.ajax that has more events to control the request, setting what should be done before and/or after it is sent - $.ajax Events.

$(function() {
  $("#solucoesFormulario").on("submit", function(event) {
    event.preventDefault();

    var data = $(this).serialize();
    $.ajax({
      url: "carregamentos/solucoes.php",
      type: "post",
      data: data,
      
      // chamada antes de enviar a requisição
      // alteramos para mostra a imagem
      beforeSend: function(xhr) {
        $(".carregando").css('visibility', 'visible');
      },
      
      // chamada quando a requisição termina (seja com erro ou OK)
      // alteramos e escondemos a imagem
      complete: function(jqXHR, textStatus) {
        $(".carregando").css('visibility', 'hidden');
      },
      
      success: function(data, textStatus, jqXHR) {
        alert('Mensagem enviada com sucesso!');
      }
    });
  });
});
.carregando{ visibility: hidden }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<img class='carregando' src='http://i.stack.imgur.com/xwRrg.gif' alt='' />
<form id="solucoesFormulario" action="#">
  <!--
    inputs
  -->
  <button type='submit'>Enviar</button>
</form>

Browser other questions tagged

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