1

Let's set up the structure first.

message.php

<div class="msgcontent content" id="bodycontent">
  <div class="getmsglist"></div>
</div>
<script>    
  setInterval(function(){
    $('.getmsglist').load('processes/messagelist.php');
  }, 500);
</script>

messagelist.php

<?php while($mat = $stmt->fetch()){ ?>
  <div class="messagebox" this-chat="<?php echo $mat['mem_id']; ?>">
      // Other Stuffs
  </div>
<?php } ?>

So above we can see that in message.php page the data gets loaded on getmsglist div from the messagelist.php page. On messagelist.php the attribute this-chat contains the user id. I want this user id to be fetched via AJAX. Currently, what I tried returned same user id for all rows. I need to fix that.

What I tried...!

$(".msgcontent").click(function() {
  var memid = $(".messagebox").attr("this-chat"); // doesn't work (fetches same id for all rows)
  //var memid = $(this).children(".messagebox").attr("this-chat"); // this returned undefined as well
  var dataString = {
    memid: memid
  };
  console.log(dataString);
});

The $(".messagebox") doesn't work here and it returns same user id for all rows. I tried "$(this)" instead but that returned undefined as it tries to fetch attribute of div ".msgcontent" which does not exist. How can I fetch this attribute value different for all rows?

2
  • .msgcontent is a wrapper div, which wraps your .messagebox items, what do you expect when click on it? Commented Apr 27, 2020 at 18:41
  • @u_mulder it opens up a modal and I want the id to fetch the relative content and display in the modal via ajax. I expect that when I click on it I get the respective value of each row from the this-chat attribute. Commented Apr 27, 2020 at 18:48

1 Answer 1

2

Instead of requesting all $('.messagebox') you should be able to select a single .messagebox by delegating the click handler with .on().

$('.msgcontent').on('click', '.messagebox', function() {
    var memid = $(this).attr('this-chat');
    var dataString = { memid: memid };

    console.log(dataString);
});

This way your click handler is bound to the container .msgcontent but delegated to .messagebox. This way the handler can be bound before there's actual content loaded.


Now I'm not entirely certain about the custom attribute this-chat. It's more logical to use data-chat.

var memid = $(this).data('chat');

The data attributes will be converted automatically if you need an integer instead of a string. But first try to actually get your object in the console log.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.