weggie
weggie

Reputation: 447

Adding dropdown options with JSON object

I'm using ColdFusion 10 to grab data via AJAX depending on the drop-down that is selected.

<script>
function loadQuery() {
    var assign = $("#fcbCountry").val();
    $.ajax({
        type: 'get',
        url: 'http://127.0.0.1/WMT/model/getCandidate.cfc',
        data: {
            method: 'getRegions',
            country: assign
        },
        dataType: 'json',
        async: false,
        success: function (result) {

            var PosVar = result.DATA[0][1];
            alert(PosVar);
        }
    });

};
</script>

The value of #fcbCountry is passed to the CFC and that returns JSON back to the page. I am confirming this by using the alert function to view the data.

The data is returned in what might be called ColdFusion JSON format:

Data:

{"COLUMNS":["STRVALUE","STRDISPLAY"],"DATA":[[0,null],[1,"Central"],[2,"Central-Detailee"],[3,"East"],[4,"North"],[5,"South"],[6,"Southwest"],[8,"West"]]}

I would like to loop over the JSON result and create drop-down options for another select box in the form.

I tried to piece together an example but when I try this:

<script>
function loadQuery() {
    var assign = $("#fcbCountry").val();
    $.ajax({
        type: 'get',
        url: 'http://127.0.0.1/WMT/model/getCandidate.cfc',
        data: {
            method: 'getRegions',
            country: assign
        },
        dataType: 'json',
        async: false,
        success: function (result) {

            var PosVar = result.DATA[0][1];
            alert(PosVar);
        }
    });

    var options = $("#fcbRegion");
    $.each(result, function () {
            options.append($("<option />").val(this[index]]).text(this.STRDISPLAY));
    });

}
</script>

I get an error that the loadQuery function is not defined.

Upvotes: 0

Views: 1341

Answers (1)

Chamika Sandamal
Chamika Sandamal

Reputation: 24302

Your code should like following,

function loadQuery() {
    var assign = $("#fcbCountry").val();
    $.ajax({
        type: 'get',
        url: '/WMT/model/getCandidate.cfc',
        data: {
            method: 'getRegions',
            country: assign
        },
        dataType: 'json',
        success: function (result) {
            var options = $("#fcbRegion");
            $.each(result.DATA, function () {
                options.append($("<option />").val(this[0]).text(this[1]));
            });
        }
    });
}

loadQuery();

Upvotes: 2

Related Questions