php chat room script code example
Example 1: create a php live chat without no load
//Updates the chat
function updateChat(){
$.ajax({
type: "GET",
url: "update.php",
data: {
'state': state,
'file' : file
},
dataType: "json",
cache: false,
success: function(data) {
if (data.text != null) {
for (var i = 0; i < data.text.length; i++) {
$('#chat-area').append($("<p>"+ data.text[i] +"</p>"));
}
document.getElementById('chat-area').scrollTop = document.getElementById('chat-area').scrollHeight;
}
instanse = false;
state = data.state;
setTimeout('updateChat()', 1);
},
});
}
Example 2: chat session in chatbox in php
var lastTimeID = 0;
$(document).ready(function() {
$('#btnSend').click( function() {
sendChatText();
$('#chatInput').val("");
});
startChat();
});
function startChat(){
setInterval( function() { getChatText(); }, 2000);
}
function getChatText() {
$.ajax({
type: "GET",
url: "/refresh.php?lastTimeID=" + lastTimeID
}).done( function( data )
{
var jsonData = JSON.parse(data);
var jsonLength = jsonData.results.length;
var html = "";
for (var i = 0; i < jsonLength; i++) {
var result = jsonData.results[i];
html += '<div style="color:#' + result.color + '">(' + result.chattime + ') <b>' + result.usrname +'</b>: ' + result.chattext + '</div>';
lastTimeID = result.id;
}
$('#view_ajax').append(html);
});
}
function sendChatText(){
var chatInput = $('#chatInput').val();
if(chatInput != ""){
$.ajax({
type: "GET",
url: "/submit.php?chattext=" + encodeURIComponent( chatInput )
});
}
}