skip to Main Content

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


  1. Chosen as BEST ANSWER

    Based on your comment on nested object and some further search, I found the solution. the code is now

    var SsCategorie = JSON.parse(SousCategorie);
    var taille = SsCategorie.SousCategorie.length;
    var i = 0;
    $('#majSSCat').empty();
    for(i ; i < taille ; i++) {
        $('#majSSCat').append('<option>'+ SsCategorie.SousCategorie[i].SousCat_Nom 
        +'</option>') ; 
                                
    }
                        
    

  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search