2

I am trying to pass values from a multiple select listbox through Ajax to PHP. I saw some examples in Jquery and JSON, however I am trying to accomplish this just in plain old javascript (Ajax). Here is what I have so far (simplified):

Ajax:

function chooseMultiEmps(str)
  {
    var mEmpList2 = document.getElementById('mEmpList'); //values from the multi listbox
    for (var i = 0; i < mEmpList2.options.length; i++) //loop through the values
    var mEmpList = mEmpList2.options[i].value;  //create a variable to pass in string
    if (window.XMLHttpRequest)
    {
       xmlhttp = new XMLHttpRequest();
    }
    else
    {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function()
   {
   if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
   {
      //specific selection text
      document.getElementById('info').innerHTML = xmlhttp.responseText; 
   }
  }
  xmlhttp.open("POST", "myPage.php", true);
  xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  var queryString = "&mEmpList=" + mEmpList; //query string should have multiple values
  xmlhttp.send(queryString);
}

I can run an alert(mEmpList) and get each value in individual message boxes, however when I retrieve and echo the $_POST['mEmpList'], I get only the first value. Also, when I alert(queryString), I get only one value.

I think I need to create a comma delimited array, and then pass that through the query string. From there, I can use the PHP implode/explode feature to separate the values. Any assistance would be greatly appreciated.

1 Answer 1

2

here:

for (var i = 0; i < mEmpList2.options.length; i++) //loop through the values
var mEmpList = mEmpList2.options[i].value;  //create a variable to pass in string

you are redefining your mEmpList over and over again, that means only the last value is send

You could do:

var mEmpList = '';
for (var i = 0; i < mEmpList2.options.length; i++) { //loop through the values
    mEmpList = mEmpList +','+ mEmpList2.options[i].value;  //create a variable to pass in string
}

Also your queryString is not ok, no need for &

var queryString = "mEmpList=" + mEmpList;

That way at the end you will have all values delimite by comma ,

In PHP you can use explode to loop each value:

<?php
    $string = explode(',' $_GET['mEmpList']);
    for($i=1; $i<count($string); $i++){
        echo $string[$i]."<br />";
    }
?>
Sign up to request clarification or add additional context in comments.

1 Comment

For anyone else, to get just the selected values in the multi-listbox, you need to add: if (mEmpList2.options[i].selected) {... concatenate comma... } between the javascript for loop

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.