JSFiddle - React, Tailwind, and code Playground
HTML
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>UDP Chat</title>
<!-- including JQuery just to simplify things -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
<div id="chat">
</div>
<script type="text/javascript">
$(window).ready(function(){
var chat_id = 1;
init_chat(chat_id, "chat");
});
</script>
</body>
</html>
JavaScript
var chat_room_id = undefined;
var last_received = 0;
/**
* Initialize chat:
* - Set the room id
* - Generate the html elements (chat box, forms & inputs, etc)
* - Sync with server
* @param chat_room_id the id of the chatroom
* @param html_el_id the id of the html element where the chat html should be placed
* @return
*/
function init_chat(chat_id, html_el_id) {
chat_room_id = chat_id;
layout_and_bind(html_el_id);
sync_messages();
}
/**
* Asks the server which was the last message sent to the room, and stores it's id.
* This is used so that when joining the user does not request the full list of
* messages, just the ones sent after he logged in.
* @return
*/
function sync_messages() {
$.ajax({
type: 'POST',
data: {id:window.chat_room_id},
url:'/chat/sync/',
dataType: 'json',
success: function (json) {
last_received = json.last_message_id;
}
});
setTimeout("get_messages()", 2000);
}
/**
* Generate the Chat box's HTML and bind the ajax events
* @param target_div_id the id of the html element where the chat will be placed
*/
function layout_and_bind(html_el_id) {
// layout stuff
var html = '<div id="chat-messages-container">'+
'<div id="chat-messages"> </div>'+
'<div id="chat-last"> </div>'+
'</div>'+
'<form id="chat-form">'+
'<input name="message" type="text" class="message" />'+
'<input type="submit" value="Say"/>'+
'</form>';
$("#"+html_el_id).append(html);
// event stuff
$("#chat-form").submit( function () {
var $inputs = $(this).children('input');
var values = {};
$inputs.each(function(i,el)...