将选择框的选定值作为字符串发送给PHP

I'm using Select2 3.4.5 for create select boxes,

I use this code for creatre a Multi-Value Select Boxe and everything is fine.

<select id="e1" name="mydata" multiple>
  <option value="D1">Data1</option>
  <option value="D2">Data2</option>
  <option value="D3">Data3</option>
</select>

...

<script>
     $("#e1").select2();
</script>

For get multiple selected values of select box in php I have to modify name="mydata" by name="mydata[]", and in PHP I get values by this code:

<?php
foreach ($_POST['mydata'] as $names) {
    print "You are selected $names<br/>";
}

?>

But my question: How can I send selected values of select box to PHP as string to recover in php like this : 'D1,D2,D3' , and thanks.

Edit:

I want to send the data as string, not receive it as an array then change it as string

Server-side with PHP

Ideally you would do this with PHP once the value is sent. To convert the selected items just want to implode the array

$names=implode(',', $_POST['mydata']);

Where $_POST['mydata'] is an array

[0]=>'D1',
[1]=>'D2',
[2]=>'D3'

implode(',', $_POST['mydata']) would be 'D1,D2,D3'

Client-side with jQuery

Your title says "send selected values of select box to PHP as string". You would do that in JS by catching the submit event of the form and using .join() to change the value of that field.

$('#formid').on('submit', function(){
    $('#e1').val($('#e1').val().join(','));
});

Your form (not given) would need an id <form id="formid" ...>

If you want a client-side solution, try getting the val() and calling join():

$('#e1').val().join()

http://jsfiddle.net/gwgLV/

You can do it with javascript.

 <select id="e1" name="mydata" multiple>
  <option value="D1">Data1</option>
  <option value="D2">Data2</option>
  <option value="D3">Data3</option>
</select>
<button id="but" onclick="now()">Show selected values</button>

javascript code

function getSelectValues(select) {
      var result = [];
      var options = select && select.options;
      var opt;

      for (var i=0, iLen=options.length; i<iLen; i++) {
           opt = options[i];

           if (opt.selected) {
                 result.push(opt.value || opt.text);
           }
      }
      return result;
 }

 function now(){
     var el =  document.getElementsByTagName('select')[0];
     var x = getSelectValues(el);
     alert(x);
 }

Demo here

Instead of alert store in a variable and send it along with the rest of the form data. Or you can use join (as mentioned in other answers ) to send it over post to php.