I'm doing chatroom project, and trying to update user status with ajax.
the problem is that a user may have multiple friends, so first i use twig for loop to show all friends, like this, function getLastActivity() is to get user's last online time, if it is bigger than current time, then show the user is online.
{% for user in users%}
{% if app.user.name != user.getName() %}
<div id="status">
{% if getLastActivity(user.getId()) > date("now + 8 hours - 10 seconds") %}
<span class="online_icon"></span>
{% else %}
<span class="online_icon offline"></span>
{% endif %}
</div>
{% endif %}
{% endfor %}
i am not really good at ajax, if there is something strange please let me know. my idea is to update status field every 3 sec. but it can only update the first friend.
My guess is that because, in twig template i only write one time, so it didn't update the rest of the friends.
$(document).ready(function () {
setInterval(function(){
update_status();
}, 3000);
function update_status()
{
$.ajax({
success:function(){
$('#status').load(" #status");
}
})
}
})
i have inspired by this article, Change Twig Template variable with AJAX, but not sure how to implement this in my problem.
my question is, is it possible to use ajax to update all the friends status, or there is a better way to achieve this.
thanks
The problem you have is that you create an element for each user with the ID status. An ID is a unique identifier, yet you use the same for each element.
What you could do is, for example, create the element with the id based on the user obj:
{% for user in users%}
{% if app.user.name != user.getName() %}
<div id="status-{{ user.id }}">
{* ... *}
</div>
{% endif %}
{% endfor %}
I don't know what exactly your update_status() function looks like, but you will need to get the user ID somehow. You can either return it in for the ajax, like so:
$.ajax({
success: function(userId){
$('#status-' + userId).load(" #status");
}
})
or you loop over all elements and you will have the id using el.attr('id').