6

I'm trying to submit a dynamically generated form which includes a file upload. For this purpose, I'm getting the form fields via a DB-connection. It is possible for a field to allow multiple selected options. The form can look something like this:

<form>
<input type="text" name="xyz"> </input>
<input type="file" name="xyzfile"> </input>
<select multiple name="...">
<option value="...">1</option>
<option value="...">2</option>
...
<option>x</option>
</select>
<select name="...">
<option value="...">1</option>
<option value="...">2</option>
</select>

Unfortunately, when I use a formData-Object to submit the form, only the last selected option for a given field gets transmitted. The "multiple" attribute is somehow ignored.

This is my code:

var pId = '1';
metaForm = $('#metaForm')[0];
formData = new FormData(metaForm);
formData.append('a','saveInstance');
          formData.append('pId', pId);
$.ajax({
                  type: 'POST',
                  url: 'x.php',
                  contentType: false,
                  processData: false,
                  data: formData,

                  success: function (response) {
...

When I examine the metaForm-Object, all entries that were selected have the attribute selected = true. Is there an option I'm not seeing to get ALL the selected entries for one select-field, when using the formData-constructor? Do I have to do this manually using formData.append()? If so, how do I make sure I do not get any duplicates when using the constructor AND append()?

This is somewhat confusing.

DCH
  • 199
  • 2
  • 3
  • 13
  • 11
    Here just name your ` – Kaiido Feb 07 '17 at 08:46
  • You're right! I didn't think of that. Your comment was actually the answer, thanks! – DCH Feb 07 '17 at 08:50
  • 1
    @Kaiido, even though the answer is basically the same as the other question, I disagree that this question is an exact duplicate. The other question is about checkboxes, and this is about multiple select; and since I was wondering how to solve this for a multiple select, your one sentence answer in the context of this question was far more helpful to me than the accepted answer on the other. – peregrination Jun 14 '17 at 21:02

1 Answers1

1

You can serialize your form data before posting like below code:

var formPostData  = $("#formID").serialize();
Indhu
  • 371
  • 1
  • 5
  • 18
  • 1
    i would be very glad if u answer this question. (https://stackoverflow.com/questions/51758955/inserting-data-of-multiple-fields-into-database-table-using-formdata-class-of-js)[Link]. – muneeb_ahmed Aug 16 '18 at 12:06