In my online-chat project using Codeigniter, jQuery, AJAX I have a function that runs every 1 second which retrieves chat with delivered status = 0
$.post("<?php echo base_url(); ?>chat/admin_chat/get_chat",
{
user_id : $('.hide_me').text(),
username : $('.username').text()
},
function(data){
if (data != "") {
$('#chat_window').append(data);
$('#chat_window').scrollTop($('#chat_window').prop("scrollHeight"));
}
}
);
and there is another function which is used to get the chats with delivered status = 1 (or old chats),
$(document).on('click','.user',function (e) {
e.preventDefault();
$('.username').html($(this).text());
$('.hide_me').html($(this).attr('id'));
$('.username').show();
$('.log_username').hide();
$("#input").removeAttr("readonly");
var user = $(this).attr('id');
$("#chat_window").html('');
$.post("<?php echo base_url(); ?>chat/admin_chat/get_old_chat",
{
user_id : $('.hide_me').text(),
username : $('.username').text()
},
function(data){
$('#chat_window').append(data);
$('#chat_window').scrollTop($('#chat_window').prop("scrollHeight"));
}
);
});
which is called when clicked on the username . The result of both AJAX calls are appended to a div. The problem I face now is sometimes when I click on the username, the chats that are not delivered is getting appended to the div before the old chats which is not what I want . I need the old chats to be appended to the div before the new chats, when clicked on the username. Could someone please suggest a way to fix the issue?
At last I found a way to fix the issue.
<span id='old_chat_appended' hidden=""></span>
. Modified the get_old_chat
function a little bit by changing the value of span to 0 and 1. After e.preventDefault()
, added
$('#old_chat_appended').text('0')
and after appending data to div using $('#chat_window').append(data)
, added
$('#old_chat_appended').text('1')
.
At last in the get_chat
function, which runs every 1 second, added
if($('#old_chat_appended').text() == 1) { $('#chat_window').append(data); }
The application is working as expected. The old chats are getting appended to the div before the new chats.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.