First of all im sorry for my bad English. im from Sri Lanka and im bad in English. I'm trying to create a chat site. but i have a problem checking for m=new messages. i used jquery setInterval() and ajax to check messages.
function chat() {
var fid = $('#send').data('id');
$.ajax({ url: "php/control/chat.php", type: 'post', dataType: 'json', data: { fid: fid }, success: function (obj) {
if(obj){
browser.find('.chat-view .seen').hide();
browser.find('.user-chat .chat-view').append(function () {
var msgs = '';
for( var i = 0; i < obj.length; i++) {
msgs += '<div class="user u2 d-flex flex-row">' +
' <span class="msg">' +
' <span class="text">' + obj[i].msg + '</span>' +
' <span class="time">' + nowTime(obj[i].sent) + '</span>' +
' </span>' +
'</div>';
}
return msgs;
});
browser.find('.chat-view').animate({scrollTop:browser.find('.chat-view')[0].scrollHeight});
}
}
});
}
setInterval(function () {
if(browser.find('div.chat-view').hasClass('chat-view') && browser.css('display') == 'block') {
chat();
}
}, 500);
i set to reply 0 from php when there is no new messages to reduce data usage. This works fine. but when there was no messages it still use 370 bytes for 1 reply and its about 45KB for a minute.
I checked facebook in chrome inspect and found out they are using a method to send a request to the server and wait for a new message or notification. server reply for that request only if there is something new. i tried using php sleep() function but i think it might cause a DoS attack on server. i cant check on WAMP because it only allow one request at one time. Please help me if someone know how to wait for a request without causing the server to stuck.