I’m trying to feed a drop down list based on a selection in a first drop down ( first defines a category, the second should list the subcategory.
Here is my code :
<script type="text/javascript">
$(document).ready(function(){
$("#majCat").change(function(){
var selectCat = $(this).val()
alert("TU AS CHOISI " + selectCat);
$.ajax({
url: 'populate_SousCategorie pour Ajax.php',
method: 'post',
data: {Cat: selectCat},
success: function(SousCategorie){
alert("retour" + SousCategorie );
var SsCategorie = JSON.parse(SousCategorie);
alert (SsCategorie);
var taille = SsCategorie.length;
alert ( "taille 2 : " + taille );
var i = 0;
alert ( "id1 " + i );
for(i ; i < taille ; i++) {
alert ( "step " + i );
alert ( "id " + SsCategorie[i].SousCat_Nom);
}
}
})
})
})
</script>
The return I can see from the external call shows the following :
{"SousCategorie":[{"sousCat_Id":"40","SousCat_Nom":"Carburant"},{"sousCat_Id":"41","SousCat_Nom":"Amendes"},{"sousCat_Id":"42","SousCat_Nom":"Entretien"},{"sousCat_Id":"43","SousCat_Nom":"Assurances"},{"sousCat_Id":"44","SousCat_Nom":"Achat"},{"sousCat_Id":"73","SousCat_Nom":"CarWash"}]}
After the alert statement after JSON.parse shows :
[object Object]But when I try to define the size of the object , SsCategorie.length the alert statement shows :
taille 2 : undefined
And the for loop is not working .
What is wrong, what is missing.
2
Answers
Based on your comment on nested object and some further search, I found the solution. the code is now
For debugging it is recomended to use the
console.log
statement. I assume your object has nested objects inside which can not be shown in an alert.You can’t use the length method on an object. It is an array method.