How to render json array data in dropdown with group options

How to render json data like

var data  =   {
    "FilterName": "Developer2",
    "FilterValues": [

Open in new window

in Dropbox having group by  option, the data is basically coming from ajax post and I want to create the select dropdown in document ready function :

<select name="example-optgroup" multiple="multiple" size="5">
      <optgroup label="Group One">
            <option value="option1">Option 1</option>
            <option value="option2">Option 2</option>
            <option value="option3">Option 3</option>
      <optgroup label="Group Two">
            <option value="option4">Option 4</option>
            <option value="option5">Option 5</option>
            <option value="option6">Option 6</option>
            <option value="option7">Option 7</option>
Puneet AroraFounderAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Ray PaseurCommented:
Please give us a little more to go on here.  There is zero correlation between the code snippet (a JSON string showing an object with an embedded array) and the HTML <select> example, with its optgroups and options.  

It would be helpful if you could show us how the JSON string data elements should line up with the HTML tags.  

How does Dropbox come into play?

What is the role of PHP in this question?

Where does the JSON string come from?  Can you show us the URL we can use to acquire the test data?  If you can show us the actual inputs and the desired outputs, using a genuine data set we can almost certainly show you the JavaScript code you need to achieve the results.

Thanks, ~Ray
Puneet AroraFounderAuthor Commented:
Dear Ray Paseur

The json comes from a ajax call , the data is like this :
    "0": {
        "FilterNameID": "4",
        "FilterName": "PosteD By",
        "CategoryBID": "18",
        "FilterValues": {
            "FilterValue0": "Authorised Dealership",
            "FilterValue1": "Used Car Dealers",
            "FilterValue2": "Owner",
            "FilterValue3": "Owner",
            "FilterValue4": "Builder"
    "3": {
        "FilterNameID": "5",
        "FilterName": "Fuel Type",
        "CategoryBID": "18",
        "FilterValues": {
            "FilterValue0": "Petrol",
            "FilterValue1": "Diseal",
            "FilterValue2": "CNG",
            "FilterValue3": "LPG"

This is jquery code :

      $("#p17").dropdownchecklist( {icon: {}, emptyText: "Empty...", width: 300 } );

            var fk_i_id = $('#p15').val();
            var  test = $('#p15').text();
            var urlbase = 'api1.php?getlist=filtermulti&';
            var count = 0;
            var catarr = [];

            $('#p15 option:selected').each(function(){
                        catarr.push({value:$(this).val(), text:$(this).text()});
                   if (count==0)
                        urlbase = urlbase + 'id='+$(this).val();


                        urlbase = urlbase + '&id'+count+'='+$(this).val();


                   count = count +1;

            var subcats = JSON.stringify(catarr);

            urlbase = urlbase + '&cats=' + subcats;

            if(fk_i_id !== 0)

            var result = "";
                         type: 'post',
                         url: urlbase,
                         contentType: 'application/json',
                         datatype: 'json',
                         data: {id:fk_i_id, cats: subcats},

                          success: function(data){
                          var opts = $.parseJSON(data);
                              var count = 0;
                              $.each(opts, function(i, d) {
                                                            //result += '<optgroup label="'  + catarr[count].text + '">';

                                       result += '<optgroup label="'+d.CategoryBID +">>"+d.FilterName + '">';
                                                         var i = 1;
                                       $.each(d.FilterValues, function(index, value) {
                                          // var inc = 'FilterValue' + i;
                                       //    console.log(index);
                                          // console.log(;
                                           result += '<option value="' + d.FilterNameID + '">' + value + '</option> ';
                                       result += '</optgroup></optgroup>';
                           $("#p17").dropdownchecklist( {icon: {}, emptyText: "Select a value ...", width: 300 } );



How does Dropbox come into play?   : Dropbox  = DropDown
greetings Puneet Arora, , I have spent some time going through the jquery code u posted here, and It is NOT well formed, and there are many inconsistencies, and even some outright mistakes  like the line -
    result += '<option value="' + d.FilterNameID + '">' + value + '</option> ';

this can not be correct, as if they pick ANY of the options it will ALWAYS return the same value identical value for ALL different choices! !

Next I can not see how you declare the AJAX as a -
    $.ajax({ type: 'post',
A   "POST" type, , ,  and then you go through a real mix up mess of code to build a "GET" type of url in -
      $('#p15 option:selected').each(function(){
which uses an array? ?

If you use the "POST" type of ajax, jquery can almost automatically build the send data for you as a single POST , instead of your mixed up GET and POST code for ajax you have.

I have had very much trouble in getting PHP to correctly use the AJAX -
     contentType: 'application/json'
in PHP, it is my opinion that you should not use that content type, and just let PHP use the standard POST content, there is really no advantage for PHP to try and use the  -
   contentType: 'application/json'

I do not think I can fix this code by so changes in you code base, you should probally start over and use another thinking and code ops for this to be understandable and workable.
Protecting & Securing Your Critical Data

Considering 93 percent of companies file for bankruptcy within 12 months of a disaster that blocked access to their data for 10 days or more, planning for the worst is just smart business. Learn how Acronis Backup integrates security at every stage

Oh, another thing - you say -
   "I want to create the select dropdown in document ready function "

and yet you do not have any code in the document ready function, to set up your select options, that I can see.
Puneet Arora, ,  OK, I had hoped you would ask questions about how to do this, but since you did not, I had time today so I did some code in javascript and PHP, that may show you some AJAX techniques to do this sort of thing. I looked at the JSON that you had that starts with -
        "0": {
            "FilterNameID": "4",

And your FORMAT of included data can not be useful for this kind of data transfer and select populate, first in the key value pairs, your keys are numbers as strings, this is not going to work correctly in PHP or javascript.   And your key value pairs for -
     "FilterValue1": "Used Car Dealers"
can not be useful for this kind of operation, so I changed it in PHP to -

$apiData = array(array('fID'=>4,'fName'=>'PosteD By','catBID'=>18,
    'fValues'=>array("pb0"=>"Authorised Dealership",
      "pb1"=>"Used Car Dealers",
    array('fID'=>5,'fName'=>'Fuel Type for','catBID'=>18,

although I do not see any use for the 'fID' key, I left it in there.

below is the PHP that goes into the api1.php  ajax page
ini_set('display_errors', 1);

header('Cache-Control: no-cache');
// Change the Type to text/plain
// In AJAX no html page is returned just data as text
header('Content-Type: text/plain');

// IMPORTANT, always check for the $_POST that is nessary, 'id' in this case
if (!isset($_POST['id'])) {
// if POST is incorrect send back HTML error page for search engines
  header('Content-Type: text/html');
  echo '<html><head><title>ERROR: Server unable to respond</title></head>
  <body><h2>ERROR: Server unable to respond due to lost transfer data: errorcode: eld14</h2></body></html>';
  } elseif ($_POST['id'] == 'init') {
// The post id of 'init' means that the select has to be populated on page startup
// I have changed your API data to something that makes some sense
  $apiData = array(array('fID'=>4,'fName'=>'PosteD By','catBID'=>18,
    'fValues'=>array("pb0"=>"Authorised Dealership",
      "pb1"=>"Used Car Dealers",
    array('fID'=>5,'fName'=>'Fuel Type for','catBID'=>18,

  echo json_encode($apiData);// change to TEXT data as a JSON CSV String
  } elseif ($_POST['id'] == 'selVal') {
// The post id of 'selVal' means that the select has sent up values to PHP
  if (isset($_POST['values'])) {// check for the post 'values'

	$aryInfo = array();// $aryInfo will be formed to report the select values back to ajax
	for ($i = 0; $i < count($_POST['values']); ++$i)
// $_POST['values'] is an array of all values selected in the select
      $aryInfo['rf'.$i] = $_POST['values'][$i];// build name - value pairs for the JSON
	$apiData = array(array('fID'=>0,'fName'=>'submit By','catBID'=>21,
    "fValues"=>array("sb0"=>"Test Submit","sb1"=>$_POST['values'])),
    array("fID"=>1,"fName"=>"return for","catBID"=>21,
    "fValues"=>$aryInfo));// array("ft0"=>"Cancel")

    echo json_encode($apiData);
    } else 'ERROR: NO VALUES';
  } else echo 'ERROR: Invalid POST ID to PHP';

Open in new window

to initialize the select, all I do is output $apiData with json_encode( )
     echo json_encode($apiData);
ask questions if you have trouble with this
This next is the browser page code for select-fill.html
I could not get or understand your jquery javascript for the select data info collection. In a multi select , the input "value" is a CSV string like  "pb1,pb2,ft0" of all selected options. I use a standard jquery AJAX with a      dataType: "html" .

you use a change method for the select -
BUT for a multi select, this is BAD OPERATION, as each choice in a multi select will file that event.

code below
<!doctype html>
<html><head><title>jQuery Ajax fill Select</title>
<script src=""></script>

<script>/* <![CDATA[ */

function tester(op1) {
// this function will just show you the way a multi select will form the value as a CSV string
if(!$('#sel-cars1').val()) {alert("YOU MUST make Select ONE Choices"); return;}
alert( $('#sel-cars1').val());

// below is the actual AJAX in a function ajxPost(obPairs)
function ajxPost(obPairs) {
if( == "selVal") {
  obPairs.values = $('#sel-cars2').val();
  if (!obPairs.values) {alert("YOU MUST make one Select Choices"); return;}
  alert("values are "+obPairs.values);

var ajxSend = {
  type: "POST",
  url: "api1.php",
  data: obPairs,
  dataType: "html",
  timeout: 3500
var aj = $.ajax(ajxSend);

aj.done(function( phpString ) {
  if ((phpString.charAt(0) == "[") && (phpString.length > 10)) {
  var phpArray = jQuery.parseJSON(phpString);
  var opts = "";
  for (var i=0; i< phpArray.length; ++i) {
    opts += '<optgroup label="'+phpArray[i].fName+' '+phpArray[i].catBID+'">';
    for (key in phpArray[i].fValues) {
      opts += '<option value="'+key+'">'+phpArray[i].fValues[key]+'</option>';
    opts += '</optgroup>';
  } else {
  alert("ERROR: server PHP has returned NON JSON string, see console Log");
});, error1, err) {// the Status IS NOT a Number, but the Type of jquery ERROR
  if (xhr.status==404) alert("ERROR from Ajax as '404 status' the "+ajxSend.url+" page was NOT on Server, \nCan NOT recover from this ERROR, This operation is NOT available!");
  else {
  alert("Ajax ERROR = \""+error1+"\", with server Status: "+xhr.status+", post-URL: "+ajxSend.url+", \npost-Data: "", \nerror because: "+err);
  if (aj.responseText) {
    }else console.log("Ajax Received Text is empty");
}// function ajxPost(obPairs)

$(function() {
ajxPost({id: "init"})

}); // $(function() {

[{"fID":"4","fName":"PosteD By","catBID":"18",
   "fValues":{"pb0":"Authorised Dealership","pb1":"Used Car Dealers","pb2":"Owner","pb3":"Builder"}
{"fID":"5","fName":"Fuel Type for","catBID":"18",

/* ]]> */</script>
<body><h3 style="text-align:center;">jQuery Ajax fill Select</h3>
Test Select - <select id="sel-cars1" name="sel-cars1" multiple="multiple" size="5">
  <optgroup label="PosteD By 18">
    <option value="pb1">Authorised Dealership</option>
    <option value="pb2">Used Car Dealers</option>
    <option value="pb3">Title Owner</option>
    <option value="pb4">Builder</option>
  <optgroup label="Fuel Type for 18">
    <option value="ft1">Petrol</option>
    <option value="ft2">Diseal</option>
    <option value="ft3">CNG</option>
    <option value="ft4">LPG</option>
</select> - <button id="but1" onclick="tester(1)">Show First Select Values</button>
Operational Select - <select id="sel-cars2" name="sel-cars2" multiple="multiple" size="5">
  <option value="0">NOT LOADED</option>
</select> - <button id="selBut" onclick="ajxPost({id: 'selVal'})"> Post Select Choices </button>

Open in new window

these two code pages work together correctly for me.
If you need other operations in this , let me know

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
MySQL Server

From novice to tech pro — start learning today.