.load Jquery letting the form be submitted

Asked

Viewed 305 times

0

I got 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 sending the form.

I switched the 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);             
 }
});

For

$(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);             

});

Thus remaining:

  $("#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 subject to return false which is my goal.

Where am I going wrong?

I used to, too:

$(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 until submitting the page and changing the page changed.

2 answers

1


You can let the $.ajax() in place of .load().

You get the return false as a return of form for the requisition ajax is asynchronous, so javascript will run ajax and continue executing the other instructions even if the ajax has not yet finished executing. That’s why it uses callbacks and promises to treat his return.


UPDATE

A way for you to prevent the standard functioning of <form> is 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 event generated in the DOM that javascript hears comes with the first parameter an object that represents the event and in this event you have access to various information about it as the .target which refers to the target GIF of the event and that method .preventDefault() which serves to prevent the default behavior from being executed.

Another example, if you use an event in <a> you can cancel the default behavior of navigating to the link on href of her using the .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://answall.com">link stackoverflow</a>


UPDATE

For automatic loading I made this guy here:

Component jQuery:

$.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();
    }
  }
}

CSS of the component:

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

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 classes full-screen-loader to create the one that covers the whole screen and the ajax-loader, the <i class="fa fa-3x fa-spin fa-spinner are classes of Fontawesome for icons.

Having the component and css loaded, use the classes in a div and an icon or image you want to use to show that you are doing a processing you just need to enable the Upload like this:

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

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

In case you didn’t want to loader.show() and loader.hide() every time you make an ajax request because you want the Download to appear on all requests, pass the parameter true and ready, in all requisitions your loader will be called. Example:

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

I make a configuration on $.ajaxSetup into the beforeSend he call the show() and in the success and error call the hide(). I have not tested if you treat the return of ajax in the methods success and error it is overwritten and erases the pattern set in $.ajaxSetup, because I treat the return of ajax in the methods .done() and .fail(), example:

$.ajax(...)
  .done(function(response) {
    // trata success
  })
  .fail(function(error) {
    // trata error
  })
  • Got it! O . post() so it shouldn’t be asynchronous. It’s not even?

  • Any http request, even if not done via $.ajax() is asynchronous.

  • Ué. but then why are you leaving the page when I use it. . post() and . load()? That was the question’s question!

  • He’s updating the page?

  • no! is switching pages as if it were a Submit straight from the form.

  • Would you use the return false to prevent the standard behavior of a form. Of a .preventDefault() at the Ubmit event

  • created an answer. has how you comment on it for me?

  • It was bad, I read in a hurry I got everything wrong and went to update my answer because I understood that I wanted to give better examples.

Show 3 more comments

0

Well, it was just a semantic mistake anyway.

I would like some guidance.

In the case of forms, post sending 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 by 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?

  • I think this will taste, I prefer to use $.ajax and pass the method: "POST". And also why I can define other properties besides just pass url and callbacks in the same $.post. I don’t know if you can define other properties in $.post, I simply see no advantage in using it instead of $.ajax.

  • Now I understand. Possibility of loaddings....

  • yes, I solved this week a way to use automatic loading with jQuery, I’ll put in my answer.

Browser other questions tagged

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