indymx
indymx

Reputation: 343

select isn't populating from JSON data

I'm having trouble with the following code.

The JSON data seems to be generated properly and the select field is being emptied of existing options as I expect it should, however, the options generated from the JSON data are not being appended to the select.

I'm not getting a console error and I am not seeing what why it's not appending.

Any suggestions?

<script>
$('#campReg').change(function() {

var $self = $(this);
$.ajax ({
url: 'php/getCamps.php', 
data: { id : $self.val()},
dataType:'JSON',
type:'POST',

    success: function(data){
            var sel = $('#otherCamps').empty();

            var toAppend = '';
            $.each(data,function(i,data){

                toAppend += '<option value="'+data.id+'">'+data.desc+'</option>';
            });
        $('#sessions').append(toAppend);
    }
    })
});
</script>

The JSON:

{data: [{id:1, desc:06/09 - 06/13 - WEATHER}, {id:3, desc:08/01 - 08/04 - TEST CAMP}]}

Upvotes: 0

Views: 89

Answers (3)

Aditya
Aditya

Reputation: 4463

Here is the Working Fiddle:

Make these two changes to your code:

$.each(data.data,function(i,data){

and

$('#otherCamps').append(toAppend);

So your code will be:

$('#campReg').change(function() {
var $self = $(this);
$.ajax ({
url: 'php/getCamps.php', 
data: { id : $self.val()},
dataType:'JSON',
type:'POST',

    success: function(data){
            $('#otherCamps').empty();

            var toAppend = '';
            $.each(data.data,function(i,data){

                toAppend += '<option value="'+data.id+'">'+data.desc+'</option>';
            });
        $('#otherCamps').append(toAppend);
    }
    })
});

Upvotes: 1

Felix
Felix

Reputation: 38102

Based on your comment, you need to use:

$('#otherCamps').append(toAppend);

instead of:

$('#sessions').append(toAppend);

since you've assigned id="otherCamps" to your select element.

Upvotes: 0

tzunghaor
tzunghaor

Reputation: 1035

I think success: function(data) receives the whole json object in data, but it has a data property that holds the actual array. So you have to iterate over data.data: $.each(data.data, ...

Upvotes: 0

Related Questions