JavaScript Function capturing only the last (element) data-attribute (django)

Viewed 28

I am working on this Django web-app where i need a button to work as a like button (which sends friend request) HTML code :

<div class="slideshow-container">
      {% for p in profiles %}
      <div class="profile-container">
              <div class ="left-div"> 
                  <div class="mySlides fade">
                    <img src="media/{{p.image}}" style="width:100%" id="user-media-img">
                    <div class="text">{{p.user_id}}</div>
                  </div>
              </div>
            <div class="right-div">
                <div class="details">
                    <h1>BIO</h1>
                    <p>{{p.bio}}</p>
                    <h1>Age:</h1><p>{{p.age}}</p>
                    <h1>Location:</h1><p>{{p.location}}</p>
                    <h1>Hobbies:</h1>
                    <p>{{p.hobbies}}</p>
                </div>
            </div>
      </div>
      <button class="btn2" onclick="sendFriendRequest(this)" id="like{{p.id}}" data-id="{{p.user_id}}">LIKE</button>
        {% endfor %}
  </div>

Let's say I have 3 profiles so the for loop will run 3 times for it and will make 3*(profile-container) divs*
PROBLEM is this data-id="{{p.user_id}}" is catching only the last profile's {{p.user_id}} no matter what which profile i am liking!
I have tried this in static html file the code is working fine then but not in django.

Here's my JavaScript code:

<script type="text/javascript">
function sendFriendRequest(id){
    //var reqtype = $(this).attr("data-id");
    var reqtype = id.getAttribute("data-id");
    alert("Capture: " + reqtype);
    payload = {
      "csrfmiddlewaretoken": "{{csrf_token}}",
      "reciever_user_id": reqtype,
    }
    $.ajax({
      type:"POST",
      dataType:"json",
      url:"friend_request/",
      timeout: 5000,
      data: payload,
      success: function(data){
          console.log("Success:" + data)
          alert('data in to payload')
          if(data['response'] == "Friend Request Sent"){
              alert('Request Sent')
          }
          else if(data['response'] != null){
            alert(data['response'])
            alert('second')
          }
          else if(data['response'] == "Already Sent!"){
              alert('Request Already Sent!')
          }
          else {
            alert('what')
          }
      },
      error: function(data){
            alert("Something went wrong: " + data)
      },      
    })

  }
</script>

EDIT 1 : Yes, there are different user_id's and html is generating different divs as per their user_id in data-id attribute.

I appreciate you help Thanks! :)

1 Answers

Why don't you send p.user_id as an argument?

<button class="btn2" onclick="sendFriendRequest('{{p.user_id}}')" id="like{{p.id}}">LIKE</button>

and in js:

function sendFriendRequest(user_id){
...
Related