Developer
Developer

Reputation: 2706

JSON response data length getting undefined error in Ajax?

I want to get the length of language in JavaScript alert box -

See screenshot-

Ajax Response -

enter image description here

enter image description here

My Ajax code -

function search_menu(){
    $.ajax({
        type: 'post',
        url: rootUrl() + "rest_apis/search_menu.json", 
        cache: false,        
        success: function(res){ //alert(data.data[0].language[142]);
            var len = res.data[0].language.length; 
            alert(len); //Showing undefined
        },
        contentType: 'application/json',
        dataType: 'json'
    });
}

I am just alerting alert(lang) its showing undefined. Actually in language having 36 record. why its showing undefined?

Upvotes: 2

Views: 13958

Answers (4)

hari
hari

Reputation: 1963

Use Object.keys().forEach();.count your json length.....CHeck to click here....

var json={"data":[{"language":{"190":"english","191":"gujarati"}}]};
var length=0;
Object.keys(json.data[0].language).forEach(function(key) {
  length++; 
});
alert(length);

Upvotes: 3

Sadikhasan
Sadikhasan

Reputation: 18600

var res={"data":[{"language":{"190":"english","191":"gujarati"}}]};
console.log( Object.keys(res['data'][0].language).length);

JS Fiddle

Upvotes: 2

Jeremy Thille
Jeremy Thille

Reputation: 26380

Try : Object.keys(res.data[0].language).length

Live example :

var res = {
        "data" : [
                {
                  "language" : { "107":"english", "142":"hindi", "143" : "indonesian"}
                }
        ]
}


alert("There are " + Object.keys(res.data[0].language).length + " languages." )

Upvotes: 8

Quentin
Quentin

Reputation: 943605

You misspelt language as languge, which is why it is undefined.

Even if you had not, it is an object not an array, so it doesn't have a length property. You'll need to count the keys to find out how many there are.

Upvotes: 1

Related Questions