perodriguezl
perodriguezl

Reputation: 430

Trying to populate Select with JSON data using JQUERY

It looks like everything has gone fine retrieving the data from the ajax call, but I having trouble to fill the select with the JSON content, it keeps firing this error in the console:

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in [{"0":"1","s_id":"1","1":"RTG","s_name":"RTG"},{"0":"2","s_id":"2","1":"IR","s_name":"IR"},{"0":"3","s_id":"3","1":"NCR","s_name":"NCR"},{"0":"4","s_id":"4","1":"RIG","s_name":"RIG"},{"0":"5","s_id":"5","1":"VND","s_name":"VND"}]

The JS is this

function populateSelect(et_id){
    $.ajax({
        url: "http://localhost/new_dec/modules/Utils/searchAvailableStatus.php",
        type: "get", //send it through get method
        data:{et_id:et_id},
        success: function(response) {
            var $select = $('#newStatus');                          
            $.each(response,function(key, value) 
            {
                $select.append('<option value=' + key + '>' + value + '</option>');
            });
        },
        error: function(xhr) {
            //Do Something to handle error
        }
    });
}

The JSON looks like this:

[{"0":"1","s_id":"1","1":"RTG","s_name":"RTG"},{"0":"2","s_id":"2","1":"IR","s_name":"IR"},{"0":"3","s_id":"3","1":"NCR","s_name":"NCR"},{"0":"4","s_id":"4","1":"RIG","s_name":"RIG"},{"0":"5","s_id":"5","1":"VND","s_name":"VND"}]

Upvotes: 0

Views: 88

Answers (2)

Kousi
Kousi

Reputation: 460

I think you need something like this.

function populateSelect(et_id){
    $.ajax({
        url: "http://localhost/new_dec/modules/Utils/searchAvailableStatus.php",
        type: "get", //send it through get method
        data:{et_id:et_id},
        success: function(response) {
            var json = $.parseJSON(response);
            var $select = $('#newStatus');                          
            $.each(json ,function(index, object) 
            {
                $select.append('<option value=' + object.s_id+ '>' + object.s_name+ '</option>');
            });
        },
        error: function(xhr) {
            //Do Something to handle error
        }
    });
}

Upvotes: 1

Kousi
Kousi

Reputation: 460

Assuming your server side script doesn't set the proper Content-Type: application/json response header you will need to parse the response to Json.

Then you could use the $.each() function to loop through the data:

var json = $.parseJSON(response);

Upvotes: 1

Related Questions