'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.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source