Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Mar 2009
    Thanked 0 Times in 0 Posts

    Unhappy Javascript chat does not show updates on link to function

    Hey guys, I'm not an expert in javascript or php so please phrase any responses as if I was really dumb. I'll try to do my best to explain my problem.

    I'm making a game that uses a chat room. I didn't make the chat room script from scratch, but I understand most of what it is doing.

    Before I get into the details, let me explain precisely what I have concluded and, when you come to the same conclusion, then we can figure out why this is happening:

    When I call the function sendChatText() from a form button, everything works. When I call the function sendChatText() from a link, the results are very unpredictable.

    The reason I want to call the sendChatText() from a link, is because I want to update the chatbox with announcements, such as when someone enters or exits the room, etc.

    By the way, I'm using IE8 if that makes a difference.

    Here is the code for calling the sendChatText() from a form:

    <span id="chat">
    		<div id="p_status"></div>
    		<div id="div_chat"></div>
    		<form id="frmmain" name="frmmain">
    			<input type="text" id="player_name" name="player_name" style="width: 100px;" />
    			<input type="text" id="txt_message" name="txt_message" style="width: 600px;" />
    			<input type="button" name="btn_send_chat" id="btn_send_chat" value="Send" onclick="javascript:sendChatText();" />
    Here is the code for calling the sendChatText() from a link, which calls another function, which calls the sendChatText()

    <MAP NAME = "Study">
    <AREA SHAPE = "RECT" COORDS = " 454,  149,  473,  376" ALT = "Push cabinet" onclick="javascript:changeRoom('SecretRoom');startTyping(PushCabinet);changeMusic(SecretRoomMusic)">
    and here is the changeRoom() function which calls sendChatText()

    function changeRoom(roomchange){
    	Announce=DefaultUser + ' has left the ' + CurrentRoom;
    //	document.getElementById('div_chat').innerHTML = '';
    //	CurrentUser='Announcement';
    //	Announce=DefaultUser + ' has entered the ' + CurrentRoom;
    //	sendChatText();
    Now here is all the javascript which updates the chat database table and prints the chat:

    var sendReq = getXmlHttpRequestObject();
    			var receiveReq = getXmlHttpRequestObject();
    			var lastMessage = 0;
    			var chatstart = 1;
    			var mTimer;
    			//Function for initializating the page.
    			function startChat() {
    				//Set the focus to the Message Box.
    				//Start Recieving Messages.
    				document.getElementById('div_chat').innerHTML += 'Starting Chat<br>';
    			//Gets the browser specific XmlHttpRequest Object
    			function getXmlHttpRequestObject() {
    				if (window.XMLHttpRequest) {
    					return new XMLHttpRequest();
    				} else if(window.ActiveXObject) {
    					return new ActiveXObject("Microsoft.XMLHTTP");
    				} else {
    					document.getElementById('p_status').innerHTML = 'Status: Cound not create XmlHttpRequest Object.  Consider upgrading your browser.';
    			//Gets the current messages from the server
    			function getChatText() {
    				if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
    					document.getElementById('div_chat').innerHTML += 'get chat text<br>';
    					receiveReq.open("GET", 'getChat.php?chat=' + CurrentRoom + '&last=' + lastMessage, true);
    					receiveReq.onreadystatechange = handleReceiveChat; 
    			//Add a message to the chat server.
    			function sendChatText() {
    				if(document.getElementById('txt_message').value == '' && CurrentUser != 'Announcement') {
    					alert("You have not entered a message");
    				if (sendReq.readyState == 4 || sendReq.readyState == 0) {
    					document.getElementById('div_chat').innerHTML += 'Sending chat info<br>';
    					sendReq.open("POST", 'getChat.php?chat=' + CurrentRoom + '&last=' + lastMessage, true);
    					sendReq.onreadystatechange = handleSendChat; 
    					var param = 'message=' 
    					if(CurrentUser == 'Announcement'){
    						param += Announce;
    						param += document.getElementById('txt_message').value;
    					param += '&name=' +  document.getElementById('player_name').value;
    					param += '&user=';
    					param += CurrentUser;
    					param += '&room=';
    					param += CurrentRoom;
    					document.getElementById('txt_message').value = '';
    					CurrentUser = DefaultUser;
    			//When our message has been sent, update our page.
    			function handleSendChat() {
    				//Clear out the existing timer so we don't have 
    				//multiple timer instances running.
    				document.getElementById('div_chat').innerHTML += 'handle set chat<br>';
    			//Function for handling the return of chat text
    			function handleReceiveChat(clear) {
    				if (receiveReq.readyState == 4) {
    				document.getElementById('div_chat').innerHTML += 'Receiving Chat<br>';
    					var chat_div = document.getElementById('div_chat');
    					var xmldoc = receiveReq.responseXML;
    					var message_nodes = xmldoc.getElementsByTagName("message"); 
    					var n_messages = message_nodes.length
    					document.getElementById('div_chat').innerHTML += 'Length of n_messages = ' + n_messages + '<br>';
    					//	for (i = 0; i < n_messages; i++) {
    					//		lastMessage = (message_nodes[i].getAttribute('id'));
    					//	}
    					//	document.getElementById('div_chat').innerHTML += 'Readying lastmessage variable' + lastMessage + '<br>';
    					//	chatstart = 0;
    						document.getElementById('div_chat').innerHTML += 'Readying lastmessage variable' + lastMessage + '<br>';
    						for (i = 0; i < n_messages; i++) {
    							//if(i == 0){
    							//	chat_div.innerHTML = '';
    							document.getElementById('div_chat').innerHTML += 'Getting in i = ' + i + '<br>';
    							var user_node = message_nodes[i].getElementsByTagName("user");
    							var type_node = message_nodes[i].getElementsByTagName("type");
    							var text_node = message_nodes[i].getElementsByTagName("text");
    							var time_node = message_nodes[i].getElementsByTagName("time");
    							if(type_node[0].firstChild.nodeValue == 'Announcement'){
    								chat_div.innerHTML += 'Incoming Announcement: ' + text_node[0].firstChild.nodeValue + lastMessage + '<br />';
    								chat_div.innerHTML += user_node[0].firstChild.nodeValue + '&nbsp;';
    								chat_div.innerHTML += '<font class="chat_time">' + time_node[0].firstChild.nodeValue + '</font><br />';
    								chat_div.innerHTML += text_node[0].firstChild.nodeValue + lastMessage;
    								chat_div.innerHTML += type_node[0].firstChild.nodeValue + '<br />';
    							chat_div.scrollTop = chat_div.scrollHeight;
    							//lastMessage = (message_nodes[i].getAttribute('id'));
    					mTimer = setTimeout('getChatText();',1000); //Refresh our chat in 1 second
    Now here is the getChat.php file which updates the messages to a single table and also saves the chat messages to an xml file which is printed from the javascript.

    //Send some headers to keep the user's browser from caching the response.
    header("Expires: Mon, 26 Jul 1997 05:00:00 GMT" ); 
    header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT" ); 
    header("Cache-Control: no-cache, must-revalidate" ); 
    header("Pragma: no-cache" );
    header("Content-Type: text/xml; charset=utf-8");
    //Check to see if a message was sent.
    if(isset($_POST['message']) && $_POST['message'] != '') {
    	$sql = "INSERT INTO chatmessages(chat_id, user_id, user_name, message, post_time) VALUES ('" . 
    			db_input($_GET['chat']) . "', '" . db_input($_POST['user']) . "', '" . db_input($_POST['name']) . 
    			"', '" . db_input($_POST['message']) . db_input($_GET['chat']) . "', NOW())";
    //Check to see if a reset request was sent.
    if(isset($_POST['action']) && $_POST['action'] == 'reset') {
    	$sql = "DELETE FROM chatmessages WHERE chat_id = " . db_input($_GET['chat']);
    //Create the XML response.
    $xml = '<?xml version="1.0" ?><root>';
    //Check to ensure the user is in a chat room.
    if(!isset($_GET['chat'])) {
    	$xml .='Your are not currently in a chat session.  <a href="">Enter a chat session here</a>';
    	$xml .= '<message id="0">';
    	$xml .= '<user>Admin</user>';
    	$xml .= '<text>Your are not currently in a chat session.  &lt;a href=""&gt;Enter a chat session here&lt;/a&gt;</text>';
    	$xml .= '<time>' . date('h:i') . '</time>';
    	$xml .= '</message>';
    } else {
    //	$last = (isset($_GET['last']) && $_GET['last'] != '') ? $_GET['last'] : 0;
    	$last = $_GET['last'];
    	$sql = "SELECT message_id, user_id, user_name, message, date_format(post_time, '%h:%i') as post_time" . 
    		" FROM chatmessages WHERE chat_id = '".db_input($_GET['chat'])."' AND message_id > " . $last;
    	$message_query = db_query($sql);
    	//Loop through each message and create an XML message node for each.
    	while($message_array = db_fetch_array($message_query)) {
    		$xml .= '<message id="' . $message_array['message_id'] . '">';
    		$xml .= '<user>' . htmlspecialchars($message_array['user_name']) . $last . '</user>';
    		$xml .= '<type>' . htmlspecialchars($message_array['user_id']) . '</type>';
    		$xml .= '<text>' . htmlspecialchars($message_array['message']) . $last . '</text>';
    		$xml .= '<time>' . $message_array['post_time'] . '</time>';
    		$xml .= '</message>';
    $xml .= '</root>';
    echo $xml;
    Now let me talk more about the unpredictable phenomenon that happens when the sendChatText() function is called from the link as opposed to the form.

    When it is called from the form, everything works fine. It updates the chat database with the message, and then prints the message as it should.

    But when sendChatText() is called from the link, it updates the chat database with the message just fine (I know this because I can see it in the mysql database). But it won't print this new message, at least not right away.

    If you call the sendChatText() function again by using a link. It will then finally show the previous announcement, but not the new one. It is always one behind for some reason. Which makes no sense to me.

    If I allow the chat to check for new messages as it normally does every second, it will continue to skip the last announcement message made in the table as if it does not exist. Even if you type several messages in the form and send them. It will show all of these, but continue to skip whatever the last announcement message was that was sent using the sendChatText() function from the link. Right now, for testing, I have it reprinting every message in the chat database. It will literally print every message but somehow skip whatever the last announcement message was, even if it is in the middle of the database. This also makes no sense to me.

    A friend of mine tried using firebugger (or some such firefox javascript debugger) and verified that the sendChatText() function from the link was indeed shown sending variables to the php but getting nothing back.

    I would think that calling the sendChatText() from a link as opposed to a form is what is making the difference. But the fact that the link sendChatText() still calls the php script and still updates the database makes me think that it should still work.

    I tried my best to explain this, so please read very carefully and please try to avoid questioning my reasons for doing certain things certain ways. That would take too long to explain. I'd like to concentrate specifically on why this is acting strangely.
    Last edited by DapperSwindler; 03-22-2009 at 12:37 AM.

  2. #2
    New to the CF scene
    Join Date
    Mar 2009
    Thanked 0 Times in 0 Posts
    EDIT: Scratch that, I thought I had fixed something but maybe not
    Last edited by DapperSwindler; 03-22-2009 at 01:43 AM.


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts