Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

278
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda