32

I have the following jQuery code. I am able to get the following data from server [{"value":"1","label":"xyz"}, {"value":"2","label":"abc"}]. How do I iterate over this and fill a select box with id=combobox

$.ajax({
    type: 'POST',
    url: "<s:url value="/ajaxMethod.action"/>",
    data:$("#locid").serialize(),
    success: function(data) {
        alert(data.msg);

                //NEED TO ITERATE data.msg AND FILL A DROP DOWN
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert(textStatus);
    },
    dataType: "json"
});

Also what is the difference between using .ajax and $.getJSON.

TheVillageIdiot
  • 40,053
  • 20
  • 133
  • 188
user373201
  • 10,945
  • 34
  • 112
  • 168

4 Answers4

47

This should do the trick:

$($.parseJSON(data.msg)).map(function () {
    return $('<option>').val(this.value).text(this.label);
}).appendTo('#combobox');

Here's the distinction between ajax and getJSON (from the jQuery documentation):

[getJSON] is a shorthand Ajax function, which is equivalent to:

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback
});

EDIT: To be clear, part of the problem was that the server's response was returning a json object that looked like this:

{
    "msg": '[{"value":"1","label":"xyz"}, {"value":"2","label":"abc"}]'
}

...So that msg property needed to be parsed manually using $.parseJSON().

namuol
  • 9,816
  • 6
  • 41
  • 54
  • 2
    I am getting the following error uncaught exception: Syntax error, unrecognized expression: [{"value":"1","label":"xyz - abc"}] at this line $(data.msg).map(function () { – user373201 May 10 '11 at 18:43
  • Ah, of course. `data.msg` is just a string, so it needs to be parsed into a JS object. I've updated the code snippet above to do this, but you should probably fix your server's response to actually return the 'msg' object directly instead of encoding it as a string first. – namuol May 10 '11 at 19:10
  • @namuol I know this is an old Q/A, and apparently you've gotten a lot of upvotes, but I had the same error when I created a JSON object, parsed & pushed data to a new array. It looked similar to what you added in your edit, except I was using names of people in the `label`, so it was like `Doe, John Q`. It gave me an error on array line 1, field 2, I think it described it as. If I simply did `$.each(dataArray, function () { $("#combobox").append($("").val(this['value']).html(this['label'])); });` it works perfectly. So I'm wondering why `parseJSON` wouldn't work. Name, maybe? – vapcguy Oct 26 '21 at 22:05
28

If your data is already in array form, it's really simple using jQuery:

 $(data.msg).each(function()
 {
     alert(this.value);
     alert(this.label);

     //this refers to the current item being iterated over

     var option = $('<option />');
     option.attr('value', this.value).text(this.label);

     $('#myDropDown').append(option);
 });

.ajax() is more flexible than .getJSON() - for one, getJson is targeted specifically as a GET request to retrieve json; ajax() can request on any verb to get back any content type (although sometimes that's not useful). getJSON internally calls .ajax().

Tejs
  • 40,736
  • 10
  • 68
  • 86
  • 1
    Just a recommendation. Create all the html and store it in a variable. When finished add all the html at once using .html() instead. It will speed up the process if you have many options. – Josh Mein May 10 '11 at 15:24
  • Thanks for the replay and comment. I am getting the following error uncaught exception: Syntax error, unrecognized expression: [{"value":"1","label":"xyz - abc"}] at this line $(data.msg).each(function(){ – user373201 May 10 '11 at 18:23
  • Im assuming that your data is coming in under the data.msg field. If that is all the data coming back, you simply do `$(data).each`. – Tejs May 10 '11 at 18:48
  • I see that the server is putting a double quotes at the start and end of the json string. what is actually returned is "[{"value":"1","label":"xyz - abc"}]". is there a js/jquery method to convert to json or do i have to use string replace to remove the beginning and ending quotes – user373201 May 10 '11 at 19:00
8

Here is an example of code, that attempts to featch AJAX data from /Ajax/_AjaxGetItemListHelp/ URL. Upon success, it removes all items from dropdown list with id = OfferTransModel_ItemID and then it fills it with new items based on AJAX call's result:

if (productgrpid != 0) {    
    $.ajax({
        type: "POST",
        url: "/Ajax/_AjaxGetItemListHelp/",
        data:{text:"sam",OfferTransModel_ItemGrpid:productgrpid},
        contentType: "application/json",              
        dataType: "json",
        success: function (data) {
            $("#OfferTransModel_ItemID").empty();

            $.each(data, function () {
                $("#OfferTransModel_ItemID").append($("<option>                                                      
                </option>").val(this['ITEMID']).html(this['ITEMDESC']));
            });
        }
    });
}

Returned AJAX result is expected to return data encoded as AJAX array, where each item contains ITEMID and ITEMDESC elements. For example:

{
    {
        "ITEMID":"13",
        "ITEMDESC":"About"
    },
    {
        "ITEMID":"21",
        "ITEMDESC":"Contact"
    }
}

The OfferTransModel_ItemID listbox is populated with above data and its code should look like:

<select id="OfferTransModel_ItemID" name="OfferTransModel[ItemID]">
    <option value="13">About</option>
    <option value="21">Contact</option>
</select>

When user selects About, form submits 13 as value for this field and 21 when user selects Contact and so on.

Fell free to modify above code if your server returns URL in a different format.

trejder
  • 17,148
  • 27
  • 124
  • 216
  • 1
    Could you please describe your answer as well as posting code? As it stands this is not particularly helpful. – marko Aug 14 '13 at 08:20
  • external brackets should be square [, ] as it is an array – J.T Feb 21 '16 at 11:10
0

In most of the companies they required a common functionality for multiple dropdownlist for all the pages. Just call the functions or pass your (DropDownID,JsonData,KeyValue,textValue)

    <script>

        $(document).ready(function(){

            GetData('DLState',data,'stateid','statename');
        });

        var data = [{"stateid" : "1","statename" : "Mumbai"},
                    {"stateid" : "2","statename" : "Panjab"},
                    {"stateid" : "3","statename" : "Pune"},
                     {"stateid" : "4","statename" : "Nagpur"},
                     {"stateid" : "5","statename" : "kanpur"}];

        var Did=document.getElementById("DLState");

        function GetData(Did,data,valkey,textkey){
          var str= "";
          for (var i = 0; i <data.length ; i++){

            console.log(data);


            str+= "<option value='" + data[i][valkey] + "'>" + data[i][textkey] + "</option>";

          }
          $("#"+Did).append(str);
        };    </script>

</head>
<body>
  <select id="DLState">
  </select>
</body>
</html>
MrMaavin
  • 1,611
  • 2
  • 19
  • 30
NewBie
  • 1