I'm building push notifications for my messaging system and have a weird bug.
I'm using an ajax to get recent messages. In my PHP script I have a while loop where I go through my results. So each
<li>
<li>
$output .= "
<li>
<img src='$profilephoto' class='rm_pp' alt=''>
<div class='imNotification'>
<script>
function getIMNotification() {
$.ajax({
url: 'getIMNotification.php',
method: 'POST',
data:{user2:'$id'},
success:function(data) {
$('.imNotification').html(data);
}
});
}
getIMNotification();
</script>
</div>
</li>
";
getIMNotification.php
user2
id
You shouldn't redefine the function in the loop. You should define the function once, and have it take the ID as a parameter. Then you can call it separately for each LI
.
You also need to put the result in the specific DIV for that message. .imNotification
selects all the DIVs with that class. You can use $id
in the ID of the DIV to target each one.
The function doesn't need to come from AJAX, you can just put this in the original HTML:
function getIMNotification(id, target) {
$.ajax({
url: 'getIMNotification.php',
method: 'POST',
data: {
user2: id
},
success: function(data) {
$('#' + target).html(data);
}
});
}
Then the PHP would be:
$output .= "
<li>
<img src='$profilephoto' class='rm_pp' alt=''>
<div class='imNotification' id='imNotification-$id'>
<script>
getIMNotification('$id', 'imNotification-$id');
</script>
</div>
</li>
";