1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
| var lastMessage = 0;
var nr = 7;
var mTimer;
$(function() {
//Set the focus to the Chat Message Box
$("txt_message").focus();
//Start Recieving Messages.
getChatText();
});
//Add a message to the chat server
$("#btn_send_chat").click(function(){
sendChatText()
});
$("#frmmain").submit(function(event){
sendChatText()
});
function sendChatText() {
if($('#txt_message').val() == '') {
alert("You have not entered a message");
return;
}
$.ajax({
type: "POST",
url: "/takeChat.php",
data: {
'last' : lastMessage,
'userID' : userID,
'name' : username,
'message' : $('#txt_message').val()
},
dataType: 'json'
})
.done(function(data) {
clearInterval(mTimer);
handleReceiveChat(data);
})
.fail(function() {
alert("Ajax failed to fetch data")
})
$('#txt_message').val('');
}
//Gets the current messages from the server
function getChatText() {
//Start Recieving Messages.
$.ajax({
type: "POST",
url: "/takeChat.php",
data: {
'last' : lastMessage,
'userID' : userID,
'name' : username
},
dataType: 'json'
})
.done(function(data) {
handleReceiveChat(data)
})
.fail(function() {
alert("Ajax failed to fetch data")
})
});
}
function handleReceiveChat(data) {
NBmessages = lastMessage;
var content = "";
for (var i = 0; i < data.messages.message.length; i++) {
content += '<font class="chat_user">' + data.messages.message[i].time + ' ' + data.messages.message[i].user + '</font> : ';
content += data.messages.message[i].text + '<br />';
if (lastMessage < data.messages.message[i].id) {
if (NBmessages > 0) {
document.querySelector("#nouveauChat").play();
}
lastMessage = data.messages.message[i].id;
}
}
$("#div_chat").append(content);
$("#div_chat").animate({ scrollTop: $("#div_chat").height()+30 }, 1000);
mTimer = setTimeout('getChatText();',10000);
} |
Partager