xetryDcoder
xetryDcoder

Reputation: 157

how to loop the ajax response?

I am trying to learn AJAX way of coding and just started using jquery. I want to fetch the subcategory from mongodb database to the option tag as soon as the (parent )ie, select tag is clicked.

Here i tried and got data but every data are in same option tag and i want them to be in different option tag. Here is the jQuery code

<script>
  $(function() {
    
    $('#subcategory-selector').on('click', function() {
      let $subCategory = $('#subCategory')
      let $category = $("#category").val()

      $.ajax({
        type: 'GET',
        url: '/getSubCategory/' + $category,
        success: function(data) {
          let result = [];
          for( let i = 0; i< data.subCategory.length; i++) {
            let obj = {
              id: data.subCategory[i]._id,
              subCategory: data.subCategory[i].subCategory,
            }
            result.push(obj)
          }
          
          $subCategory.append('<option>' + result[0].subCategory +'</option>')
          $subCategory.append('<option>' + result[1].subCategory +'</option>')
        },
        error: function() {
          alert("No sub Category found")
        }
      })
    })
  })
</script>

Here is the html. ** In this place i want my sub category inside the option element. **

               <div class="form-group">
                  <label class="form-control-label text-primary" for="example3cols2Input">Sub Category</label>
                  <select name="subCategory" id="subcategory-selector" class="form-control">
                    <option value="sub" id="subCategory"></option>
                  </select>
                </div>

The JSON i am getting as Response is:

{
  subCategory: [
    {
      category: [Array],
      _id: 609bb80061350f23301ba6b3,
      subCategory: 'hy',
      createdAt: 2021-05-12T11:12:00.035Z,
      updatedAt: 2021-05-12T11:12:00.035Z,
      __v: 0
    },
    {
      category: [Array],
      _id: 609bb80561350f23301ba6b4,
      subCategory: 'by',
      createdAt: 2021-05-12T11:12:05.886Z,
      updatedAt: 2021-05-12T11:12:05.886Z,
      __v: 0
    }
  ],
  _id: 609bb7e961350f23301ba6b2,
  category: 'Hello',
  image: 'images\\2021-05-12T11-11-37.489Z-images.jpg',
  createdAt: 2021-05-12T11:11:37.580Z,
  updatedAt: 2021-05-12T11:12:05.911Z,
  __v: 0
}

Help me to render the output in option tag.

Upvotes: 0

Views: 105

Answers (1)

Jeremy Thille
Jeremy Thille

Reputation: 26360

Try this :

for( let result of data.subCategory) {
   $subCategory.append('<option>' + result.subCategory +'</option>')
}

Upvotes: 1

Related Questions