Refreshing Chat Body For Each Of The Users
Solution 1:
This needs a complete rethink really, to be rid of all the potential bugs.
The problem you describe above is because you're creating a new timed interval every time someone clicks on a name, so gradually this builds up and you are requesting every few milliseconds instead of every second. This is unsustainable. There's no need really to be declaring intervals, functions etc etc within the "click" handler of the name. I think you're doing this because of the dependency on the user ID which results from selecting a name. However you can overcome that by assigning the value to a global variable.
Doing this means you can move all the functions outside the click handler, removing any danger of re-creating the same intervals / events multiple times. I've also changed it so it doesn't use an interval. Instead, fetch_chat calls itself again 2 seconds after the previous response is received. That way, if a fetch takes longer than normal, you don't have multiple competing fetch operations running in parallel and causing potential confusion. I also increased the time interval to something which is still reasonable, but won't overload the server.
Here's a complete rework of your code:
<script>
var currentID = null;
var chatTimer = null;
function fetch_data() {
$.ajax({
url: "select.php",
method: "POST",
success: function(data) {
$('#live_data').html(data);
fetch_chat();
}
});
}
function fetch_chat() {
$.ajax({
url: "fetch_chat.php",
method: "POST",
data: {
id: currentID
},
dataType: "text",
success: function(data) {
$('#messages').html(data);
$("div.area").show();
chatTimer = setTimeout(fetch_chat, 2000); //request the chat again in 2 seconds time
}
});
}
$(document).ready(function() {
$(document).on('click', '.first_name', function() {
currentID = $(this).data("id1");
//immediately fetch chat for the new ID, and clear any waiting fetch timer that might be pending
clearTimeout(chatTimer);
fetch_chat();
});
$("#sub").click(function() {
var text = $("#text").val();
$.post('insert_chat.php', {
id: currentID,
msg: text
}, function(data) {
$("#messages").append(data);
$("#text").val('');
});
alert(text);
});
fetch_data(); //this will also trigger the first fetch_chat once it completes
});
</script>
P.S. If you want anything faster than 2 seconds refresh, then really you probably need to consider re-architecting the solution using websockets to get full 2-way communication, so the server can "push" chat items to the client instead of the client having to poll the server.
Solution 2:
You are using setInterval, this is wrong, this will start a loop every time you click on a chat, you should have a single loop running over all your chats. Also consider using setTimeout instead of setInterval to ensure you get the response first.
Post a Comment for "Refreshing Chat Body For Each Of The Users"