Govind Shah
Govind Shah

Reputation: 81

jQuery ajax response to html issue

For my project I have created a profile page that lists profile pictures uploaded by users. Under each picture I have a "View comments" link that upon clicking shows all the comments linked to that picture object. Using an AJAX call I search the record based on the image object id and fetch the related comments.

The issue is that when I am rendering that response to HTML, clicking the view comments of one image opens all the other view comments section for other images and populates the same data to all other sections.

<div class="show">
  <a href="">
    <h6 data-id="{{item.pk}}">View Comments</h6>
  </a>
  <div id="refresh" class="menu" style="display: none;"></div>
</div>
$(document).ready(function() {
  var iden, array, array2;

  function getdata(iden) {
    var val = iden.data('id');
    console.log(val)

    $.ajax({
      url: "{% url 'fetchertwo' %}",
      type: "GET",
      data: {
        'search': val
      },
      dataType: 'json',
      success: function(data) {
        array = data.content;
        array2 = data.author;
        console.log(array);
        console.log(array2);

        $('.show').find('.menu').toggle("slide");
        $.each(array, function(i, item) {
          $('.menu').append(array[i] + array2[i] + '<br>')
          console.log(array[i], array2[i]);
        });
      }
    });
  }

  $('.show').on('click', function(event) {
    iden = $(event.target)

    console.log(iden)
    getdata(iden);
    event.preventDefault();
    $('.menu').html("")
  });

  $('#formtwo').on("submit", function(event) {
    event.preventDefault();
    if (!iden) {
      iden = $(this).find('.form-control').data('id');
    }
    var formData = $(this).serialize();
    var posting = $.post("/usercreation/picomment/" + iden, formData, function(response) {
      getdata(iden);
    });
    this.reset();
  });
});

Upvotes: 1

Views: 141

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

The issue is because you're selecting and updating all the .menu elements in the DOM. You instead need to retrieve the one which is contained within the clicked .show element, which you can achieve using find() and the iden reference you pass to the getdata() function. Try this:

iden.find('.menu').append(array[i] + array2[i] + '<br>')

Upvotes: 1

Related Questions