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

362
Visualizações
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 à 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