Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FormData doesn't include value of buttons

Consider the following snippet:

$('#myBtn').click(function(e) {
    e.preventDefault();
    
    var formElement = $(this).closest('form')[0];
    var request = new XMLHttpRequest();
    request.open("POST", "https://posttestserver.com/post.php");
    request.send(new FormData(formElement));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="POST" action="https://posttestserver.com/post.php">
  <input type="text" name="wtf" />
  <button type="submit" name="lol" value="cats" id="myBtn">
    Huh
  </button>
</form>

(Have your developer tools open and watch for HTTP requests.)

When you click on the button, any text you entered into the textbox is included in the POST request. However, the lol=cats pair from the button itself is not.

How can I make FormData include the data given by buttons?

like image 331
Lightness Races in Orbit Avatar asked Feb 04 '23 02:02

Lightness Races in Orbit


2 Answers

Because the call to FormData's constructor doesn't know that it was triggered by a click on a submit button (let alone which submit button it was), and because you only want the used submit button's values included, the submit button isn't included in the posted data. You can use FormData.append to include desired pair.

$('#myBtn').click(function(e) {
    e.preventDefault();
    var formElement = $(this).closest('form')[0];
    var formData = new FormData(formElement);
    formData.append("lol","cats");
    var request = new XMLHttpRequest();
    request.open("POST", "https://posttestserver.com/post.php");
    request.send(formData);
});
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
 <form method="POST" action="https://posttestserver.com/post.php">
      <input type="text" name="wtf" />
      <button type="submit" id="myBtn">
        Huh
      </button>
    </form>
like image 140
lucky Avatar answered Feb 06 '23 15:02

lucky


As you have already stated, FormData cannot know the button’s name. But when you catch a form submission, you can get the name through the submitter property on the event:

const form = document.querySelector("form")

form.addEventListener("submit", ev => {
    ev.preventDefault()

    const data = {}

    for (const field of new FormData(form)) {
        data[field[0]] = field[1]
    }

    // NB: we are setting "none" as a fallback in case the form
    // has been submitted without clicking a button, e.g. by 
    // hitting enter in an input field.

    data.action = ev.submitter ? ev.submitter.name : "none"

    // … and so on
})
like image 28
lxg Avatar answered Feb 06 '23 15:02

lxg