Ryne Ryne - 8 months ago 61
Ajax Question

Ajax in while loop

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>
is a 'recent message'.

In my mind it would be simple. I put an ajax function in the
<li>
and as it iterates through the while loop it will send the values received from the iteration. Below is my PHP script.

$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>
";


For example, in my
getIMNotification.php
if i just echo the
user2
value sent from my AJAX, it will echo the same value for each result. But, since it's in the while loop, shouldn't it receive new values each iteration?

Is it because of the function being called? The one value being echoed is the last
id
in the loop. Any logic as to why it's doing that?

Answer Source

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>
";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download