0
votes

I am using a form with multiple selects (using Select2) and submitting the data to the server using HTML5's Formdata object. It works well when I am sending text or files but does not work in this case.

I have given the name attribute as lbl[] as required and also specified multiple="multiple".

Does Formdata support multiple select or is there anything I am missing?

My select:

<select class="form-control theread_p_ip" name="thread_p[]" multiple="multiple" style="width: 100%"></select>

The way I am using Formdata:

 form_data = new FormData($(mydata.sform)[0]);
 ajaxoptions.data=form_data;

where ajaxoptions is the object I am passing to JQuery AJAX and $(mydata.sform)[0] selects my form

I have checked using print_r($_POST,true) and I get this:

Array
(
[thread_p] => 
[thread_lbl] => giggg
[ddemand] => json
[dtype] => json
[eltarget] => -1
[sform] => #ta-tbxnewthread
[mkey] => tbx_newthread
)

You can see that the thread_p is empty. If I specify name="thread_p" instead of using [] I get the last selected value alone.

PS: Ignore the other values in the array. Those are other parameters I am sending from the client side.

And if you wonder there is no options in select, they are loaded via AJAX by select2 which is working properly.

UPDATE: SOLVED using hackerman's fiddle: https://jsfiddle.net/95khdzp2/1/

And in server side you get the values separated by ',' which you have to separate using explode(',', $variable); if you are using PHP

2
ajaxoptions.data.mySelect2=$(".theread_p_ip").val(); ?? - Hackerman
Nope. select2 is just a plugin I am using. select2.github.io there is no variable data.mySelect2 - Vignesh T.V.
Did you even try..or maybe you already solved it?? - Hackerman
I tried. It does not work. - Vignesh T.V.
Maybe you are doing it wrong: jsfiddle.net/95khdzp2/1 ...just check the console - Hackerman

2 Answers

1
votes

As per select2 documentation, You didn't need to give name array, only give name, here name="thread_p"

As per documentation, there is an example provided,

$(".js-example-basic-multiple").select2();

<select class="js-example-basic-multiple" multiple="multiple">
  <option value="AL">Alabama</option>
    ...
  <option value="WY">Wyoming</option>
</select>

please refer https://select2.github.io/examples.html

1
votes

You could follow this logic:

var ajaxOptions = {};
ajaxOptions.data = {};
$(function(){
  $(".theread_p_ip").select2();

  $(".theread_p_ip").change(function(){
    ajaxOptions.data.mySelect2 = $(this).val();
    console.log(ajaxOptions);
  });
});

On this way, your ajaxOptions Object could update his values, based on the select2 changes.