Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

280
Visualizações
Form submission from javascript event, not form action

Ok, so this might be a little confusing question, but anyway: I have a form, targeting an external URL for validation.

<form
  id="form1"
  name="form1"
  class="formclass"
  accept-charset="UTF-8"
  autocomplete="off"
  enctype="multipart/form-data"
  method="post"
  novalidate
  action="https://www.external_url.com"
  >

However, I want to do something in the time, where the user clicks the submit button and the form gets send to the external URL. Basically, I'm trying to achieve that by deleting the action from the form there and creating an event handler:

button=document.getElementById("SubmitButton");
button.addEventListener('click', submitaction);

function submitaction() {
// Do something and THEN submit it to external URL
}

When I'm done "doing something" (e.g. maybe to display an alert before sending it), I want to take the whole form and send it to external. What do I need to do to exactly achieve the same output as the action in form?

Thanks guys!

EDIT:

I took the advice regarding the submit event listener. However, an AJAX request shall be made before submitting the form.

form1.addEventListener('submit', function(e) {
    $.ajax({
    type: 'POST',
    url: 'form_submission.php',
    data: {'check_input': input.value}, 
    success: function(response){
    if (response == true){
    alert("Thank you for your inquiry!");
    }
    }
    else {
    alert("Your input entered was incorrect.")
    e.preventDefault();
    }
    }
    }
    ); 

Somehow, the event listener just ignores my AJAX request and still submits the form. It doesn't even show the alerts, which is super strange.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Removing the action attribute won't prevent form submission, it'll only reload the page.

You should instead attach a submit event listener on the form and add the code you wish to execute before submitting in the callback:

form1.addEventListener('submit', function(){
  alert('submit!');
})
<form id="form1" name="form1" class="formclass" accept-charset="UTF-8" autocomplete="off" enctype="multipart/form-data" method="post" novalidate action="https://www.external_url.com">
  <button>submit</button>
</form>

For conditional form submission, Event.preventDefault() is used to prevent form submission:

form1.addEventListener('submit', function(e) {
  if (!input.value.length > 0) {
    console.log('You have not filled out the input field')
    e.preventDefault();
  }
})
<form id="form1" name="form1" class="formclass" accept-charset="UTF-8" autocomplete="off" enctype="multipart/form-data" method="post" novalidate action="https://www.external_url.com">
  <input id="input">
  <button>submit</button>
</form>


If you're making an AJAX request, your code should look like:

form1.addEventListener('submit', function(e) {
    e.preventDefault();
    $.ajax({
        type: 'POST',
        url: 'form_submission.php',
        data: {
            'check_input': input.value
        },
        success: function(response) {
            if (response == true) {
                alert("Thank you for your inquiry!");
                form1.submit();
            }
        }
        else {
            alert("Your input entered was incorrect.")
        }
    })
});
about 4 years ago · Juan Pablo Isaza Relatório

0

This is a small snippet, illustrating the use of a fetch-post to check the input value before submitting the form. Only if the numerical value of the input field is >0 the form will be submitted.

form1.addEventListener('submit', function(e) {
  e.preventDefault();
  fetch("https://jsonplaceholder.typicode.com/users",{
   method: 'POST',
   headers: {'Content-Type':'application/json'},
   body: JSON.stringify({usrVal:input1.value})
  }).then(r=>r.json()).then(o=>{
    if (+o.usrVal>0) form1.submit()
  })
})
<form id="form1" name="form1" class="formclass" accept-charset="UTF-8" autocomplete="off" enctype="multipart/form-data" method="post" novalidate action="https://www.external_url.com">
  <input id="input1">
  <button>submit</button>
</form>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda