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

365
Vistas
JavaScript event.preventDefault() submit button data in _POST

There is something I can not seem to find documentation on:

I have this form with multiple buttons. The buttons have their own actions associated with them and the Submit button is meant to submit data for storage. All actions are handled in PHP on the server side.

The main reason for submitting the form with a XMLHttpRequest is so that I can prevent page reload for the client.

<form action="/path/to/action.php" method="post" onsubmit="return submitForm(event)">
    <input type="text" name="comment">
    <button name="action" value="new_action">Action</button>
    <!-- more fields & buttons ... -->
    <input type="submit" name="submit" value="submitted">
</form>

The submitForm() function is like this:

function submitForm(event) {
    event.preventDefault();
    var data = new FormData(event.target);
    console.log([...data]);
    var request = new XMLHttpRequest();
    request.open("POST", event.target.getAttribute("action"), true);
    request.send(data);
    request.onreadystatechange = function() {
        if (request.readyState === 4 && request.status === 200) {
            document.open();
            document.write(request.responseText);
            document.close();
        }
    }
    return false;
}

Everything works as expected except one detail. Because of preventDefault() or the return false in onsubmit the submit / button values are not showing up in the $_POST array on the server side.

I need these values so that when buttons are clicked, certain actions trigger, but only if their associated buttons clicked and are in $_POST.

So far I have not been able to find how and why this works like it does. Anyone have any background info on this or a workaround?

Obviously I could add an onclick function to buttons that manually adds their value to submitted data if clicked but this seems to me like it should not be necessary.

about 4 years ago · Juan Pablo Isaza
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