0

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.

G4Hu
  • 338
  • 1
  • 3
  • 18
  • FormData does not add it so you will need to add it in – epascarello May 13 '22 at 18:37
  • See https://stackoverflow.com/questions/5721724/jquery-how-to-get-which-button-was-clicked-upon-form-submission for how you can get which submit button was clicked. Then you can use `data.add(button.name, button.value)`, where `button` is the submit button. – Barmar May 13 '22 at 18:57

0 Answers0