.load JQuery leaving the form to be submitted

0

I have the following js

  $("#contato").on("submit", function () {
    if($('#descricao').val() == "")   {     //verifica apena o texto
        alert("Descrição não está preenchida!");
        $('#descricao').siblings().each(function(){
          if ($(this).children('iframe').length){
             var iframe=$(this).children('iframe')[0];
             iframe.contentWindow.focus();
          }
       });
       return false;
    } 

    $.ajax({
     url: "_required/email.php",
     type: "POST",
     data: $("#contato").serialize(),
     success: function(retorno){

        if (retorno == "OK") {
          resposta = "E-mail enviado com sucesso!";
        } else {
          resposta = "Erro no envio do E-mail";
        }
       $(".resposta").css("display", "block");
       $(".resposta").html(resposta);             
     }
    });

    return false;

  }); 

This validates the submission of the form.

I changed Ajax

$.ajax({
 url: "_required/email.php",
 type: "POST",
 data: $("#contato").serialize(),
 success: function(retorno){

    if (retorno == "OK") {
      resposta = "E-mail enviado com sucesso!";
    } else {
      resposta = "Erro no envio do E-mail";
    }
   $(".resposta").css("display", "block");
   $(".resposta").html(resposta);             
 }
});

By

$(this).load ("_required/email.php", $("#contato").serialize(), function(result) {

    if (result == "OK") {
      resposta = "E-mail enviado com sucesso!";
    } else {
      resposta = "Erro no envio do E-mail";
    }
   $(".resposta").css("display", "block");
   $(".resposta").html(resposta);             

});

Looking like this:

  $("#contato").on("submit", function () {
    if($('#descricao').val() == "")   {     //verifica apena o texto
        alert("Descrição não está preenchida!");
        $('#descricao').siblings().each(function(){
          if ($(this).children('iframe').length){
             var iframe=$(this).children('iframe')[0];
             iframe.contentWindow.focus();
          }
       });
       return false;
    } 

    $(this).load ("_required/email.php", $("#contato").serialize(), function(result) {

        if (result == "OK") {
          resposta = "E-mail enviado com sucesso!";
        } else {
          resposta = "Erro no envio do E-mail";
        }
       $(".resposta").css("display", "block");
       $(".resposta").html(resposta);             

    });

    return false;

  }); 

But in this way, the form is being submitted and with ajax is not submitted because in return false that is my goal.

Where am I going wrong?

I also started using:

$(this).post("_required/email.php",{ 
   assunto : $("#assunto").val(),
   assunto : $("#nome").val(),
   assunto : $("#email").val(),
   assunto : $("#telefome").val(),
   assunto : $("#descricao").val(),
   assunto : $("#qual").val()
 },function(result){

    if (result == "OK") {
      resposta = "E-mail enviado com sucesso!";
    } else {
      resposta = "Erro no envio do E-mail";
    }
   $(".resposta").css("display", "block");
   $(".resposta").html(resposta);             

})

But that way even submitting the page and changing the page has changed.

    
asked by anonymous 09.11.2016 / 18:43

2 answers

1

You can leave $.ajax() instead of .load() .

You get return false as a return of form because the ajax request is asynchronous, so javascript will execute ajax and continue executing the other statements even though ajax has not yet finished run. So it uses callbacks and promises to handle the return of it.

UPDATE

One way to prevent default operation of <form> is by using .preventDefault() , see:

var form = document.querySelector('#myForm');

form.addEventListener('submit', function(event) {
  console.log(event);
  event.preventDefault();
});
                      
<form id="myForm">
  <button>Submit</button>
</form>

Note that every DOM-generated event that javascript listens on comes with the first parameter an object representing the event, and in that event you have access to various information about it as .target which refers to the event's target DOM and this .preventDefault() method that serves to prevent the default behavior from running.

Another example, if you use an event in a <a> you can cancel the default behavior of browsing to the link in href of it using .preventDefault() , see:

var links = document.querySelectorAll('a');

links.forEach(function(link) {
  link.addEventListener('click', function(event) {
    event.preventDefault();
    console.log(event.target.textContent);
  });
});
<a href="http://google.com">link google</a>
<a href="http://http://pt.stackoverflow.com">link stackoverflow</a>

UPDATE

For auto loading I made this face here:

jQuery component:

$.fn.loader = function (automatic) {
  var isAutomatic = automatic || false;
  var loader = this;
  var numLoadings = 0;

  if (isAutomatic) {
    $.ajaxSetup({
      beforeSend: function () {
        showLoader();
      },
      success: function () {
        hideLoader();
      },
      error: function () {
        hideLoader();
      }
    })
  }

  return {
    show: showLoader,
    hide: hideLoader
  }

  function showLoader() {
    numLoadings++;
    loader.show();
  }
  function hideLoader() {
    if ((--numLoadings) === 0) {
      loader.hide();
    }
  }
}

Component CSS:

.full-screen-loader {
  position: fixed;
  display: none;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 1100;
  background-color: rgba(255, 255, 255, 0.6);
}

.ajax-loader {
  color: black;
  opacity: 1;
  position: absolute;
  left: 50%;
  top: 50%;
  margin-left: -32px;
  margin-top: -32px;
  display: block;
}

I use this html:

<div id="general-loader" class="full-screen-loader">
  <i class="fa fa-3x fa-spin fa-spinner ajax-loader"></i>
</div>

The important thing is to use the full-screen-loader classes to create the one that covers the entire screen and ajax-loader , <i class="fa fa-3x fa-spin fa-spinner are classes of Fontawesome for icons.

With the component and css loaded, use the classes in a div and an icon or image that you want to use to show that you are processing, you only need to activate the loader like this:

var loader = $('#general-loader').loader();
loader.show(); // mostra o loader sobre a tela
loader.hide(); // esconde o loader

If you call loader.show() more than once before calling loader.hide() , you will need to call loader.hide() the same amount of times you called loader.show() to hide it again.

If you did not want to do loader.show() and loader.hide() every time you make an ajax request because you want the loader to appear in all requests, pass the parameter true and ready, in all requests its loader will be called. Example:

var loader = $('#general-loader').loader(true);

I make a setting in $.ajaxSetup to in beforeSend it calls show() and in success and error call hide() . I have not tested if you treat the ajax return in the methods success and error it is overwritten and erases the default set in $.ajaxSetup , since I treat the ajax return in methods .done() and .fail() example:

$.ajax(...)
  .done(function(response) {
    // trata success
  })
  .fail(function(error) {
    // trata error
  })
    
09.11.2016 / 18:59
0

Well, it was just a semantic error.

I would like guidance.

In terms of forms, posting and tals, which would be the most indicated form to work?

Using $ .post

   $.post ("_required/email.php", {

       assunto   : $("#assunto").val(),
       nome      : $("#nome").val(),
       email     : $("#email").val(),
       telefone  : $("#telefone").val(),
       descricao : $("#descricao").val(),
       qual      : $("#qual").val(),

   }, function(retorno){

        if (retorno == "OK") {
          resposta = "E-mail enviado com sucesso!";
        } else {
          resposta = "Erro no envio do E-mail";
        }
       $(".resposta").css("display", "block");
       $(".resposta").html(resposta);     

     }
    );

Or using $ .ajax

$.ajax({
 url: "_required/email.php",
 type: "POST",
 data: $("#contato").serialize(),
 success: function(retorno){

    if (retorno == "OK") {
      resposta = "E-mail enviado com sucesso!";
    } else {
      resposta = "Erro no envio do E-mail";
    }
   $(".resposta").css("display", "block");
   $(".resposta").html(resposta);             
 }
});

And why?

    
10.11.2016 / 15:37