Kevin
Kevin

Reputation: 2688

Pulling in JSON via AJAX to populate a Drop-Down

I am pulling in some JSON data that will vary... for instance:

Data returned could be:

[{"userID":"2779","UserFullName":" Absolute Pro-Formance"},{"userID":"2780","UserFullName":" AR Fabrication"},{"userID":"2781","UserFullName":" Banda Lucas Design Group"}]

or:

[{"orderID":"112958","OrderName":"Order ID: 112958"},{"orderID":"112957","OrderName":"Order ID: 112957"},{"orderID":"112956","OrderName":"Order ID: 112956"}]

What I am attempting to do is process this JSON to build a <select> list.

// Load in a drop-down as JSON
function LoadDropDown($url, $where, $id, $selectName){
    var $loading = '<div class="pageLoader" style="margin:0 auto !important;padding:0 !important;"><img src="/assets/images/ajax-loader.gif" alt="loading..." height="11" width="16" /></div>';
    var $t = Math.round(new Date().getTime() / 1000);
    var $container = jQuery($where);
    var options = {
            url: $url + '?_=' + $t,
            cache: false,
            type: 'POST',
            beforeSend: function(){
                    $container.html($loading);  
                },
            success: function(data, status, jqXhr){
                $html = '<select class="form-control" id="'+$selectName+'" name="'+$selectName+'">';
                $html += '<option value="0">- Select an Option -</option>';
                for(var i = 0; i < data.length-1; ++i) {
                    var item = data[i];
                    console.log(item.userID);
                }
                $html += '</select>';
                $container.html('<pre>' + data + '</pre>');
            },
            complete: function(jqXhr, status){},
            error: function(jqXhr, status, error){
                $container.slideDown('fast').html('<div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button><i class="fa fa-exclamation-triangle fa-4x pull-left"></i><p><strong>Danger Will Robinson!</strong><br />There was an issue pulling in this page. Our support team has been notified, please check back later.</p></div>');    
            }
    };
    jQuery.ajax(options);
}

The issue I am having is... #1 console.log(item.userID); always shows undefined, and #2 how can I effecitvely dynamically build the options? The returned JSON will ALWAYS contain 2 items per row and id, and a name

UPDATE

for(var $key in data){
    var $val = data[$key];
    for($j in $val){
        console.log('name:' + $j + ' = ' + $val[$j]);
    }
}

Is showing me what I need in Firefox Console... But 1 item per line, for each (for example the 1st JSON) name:userID = 1234 next line name:UserFullName = TheName

How can I get them so I can build my <options>?

With:

for(var k in data) {
    console.log(k, data[k]);
}                   

I am returned:

2955 Object { orderID="8508", OrderName="Order ID: 8508"}

and

2955 Object { userID="1355", UserFulleName="Me Myself And I"}

Upvotes: 3

Views: 2254

Answers (3)

Mir Gulam Sarwar
Mir Gulam Sarwar

Reputation: 2648

You don't need to use such messy code. Also in your Ajax setup dataType:"json"

success:function() {
    var listB=$('#yourdropdownId');
    listB.empty();  
    $.each(result, function (index, item) {
        listB.append(
            $('<option>', {
                value: item.userID,
                text: item.UserFullName
            }, '<option/>'))
         });
    }

Also the $.getJson instead of ajax if you only want retrieve json from server

$.getJSON('@Url.Action(" "," ")',
                { "youparametername": yourdata}, function (data) {
                    $.each(data, function (index, item) {
                    })
            });

Upvotes: 3

Kevin
Kevin

Reputation: 2688

Cured: Changed my loop to cycle through each item in the returned JSON, got their keys, etc...

var $dl = data.length;
for(var $i = 0; $i < $dl - 1; ++$i) {
    var $keys = Object.keys(data[$i]);
    $html += '<option value="' + data[$i][$keys[0]] + '">' + data[$i][$keys[1]] + '</option>';
}

Upvotes: 0

carter
carter

Reputation: 5432

inside the options object, make sure to use the

dataType: 'json'

Or in the success handler you can use

JSON.parse(data)

Upvotes: 1

Related Questions