Jump to content

Recommended Posts

I've been trying to figure out how chat apps work all afternoon to do dynamic data in HTML loading.  Can someone please tell me where I'm going wrong for the code flow in this script:

<script>
    function submitchat{
        if (form1.uname.value=='' || form1.msg.value==''){
            alert("fill out whole form");
            return;
        }
        var uname=form1.uname.value;
        var msg=form1.msg.value;
        var xmlhttp= new XMLHttpRequest();

        xmlhttp.onreadystatechange = function(){
            if (xmlhttp.readyState==4 && xmlhttp.status=200){
                document.getElementById('chatlogs').innerHTML=xmlhttp.responseText;
                alert("message sent");
            }

        xmlhttp.open('GET', '?page=3.2&uname='+uname+'&msg='+msg, true);
        xmlhttp.send();
    }


</script>
<form name="form1">
    enter your chat name<input type="text" name="uname">
    message: <textarea name="msg"></textarea>
    <br>
    <div id="chatlogs">Loading Chat Logs...</div>
    <a href="#" onclick="">send</a>
</form>

<?php
$uname = $_REQUEST['uname'];
$msg = $_REQUEST['msg'];
if ($msg!='' && $uname!=''){
    $chat="
	INSERT INTO chat (
	`uname` ,
	`msg`
	)
	VALUES (
	'$uname',
	'$msg'
	)";
    $result = mysql_query($chat, $con) or die (sql_death($chat));
}

for a start you are using xmlhhtp request directly. where there is nothing wrong with this, it is 2014 and you should use jquery ajax for all of your requests. have a google for jquery ajax chat room..

plus, you're never calling the function you have made

<a href="#" onclick="">send</a>  the onlick handler is empty. I am going to presume you have copied this script from a veeeeeeery old site. Like i stated before, in modern javacript you dont put event handlers direct into the html, you use event listeners

Edited by gristoi
  • 1 month later...

im gona show you an example of a very basic chat app i designed

 

the jquery

$(document).ready(function(){
	var IastID 		= 0;
	var noActivity	= 0;
	var nextRequest = 5000;
	var update = updateChat();

$('#inputField').keypress(function(e)
	{
		if (e.keyCode == 13 && !e.shiftKey)
		{	
			var text = $('#inputField').val();
			
			if(text != "")
			{
				// Assigning a temporary ID to the chat:
				$.ajax({
					type: "POST",
					url: "index.php?send=true",
					data: {  
							'function'	: 'send',
							userID		: wr.userID,
							userName	: wr.userName,
							level		: wr.level,
							text		: text.replace(/</g,'<').replace(/>/g,'>')
						 },
					dataType: "json",
					success: function(r){
						$('#inputField').val('');
						updateChat();
					},
				});

				return false;
			}
		}
	});
	
	function updateChat()
	{
		$.ajax({
			type: "POST",
			url: "index.php?hb=true",
			data: {  
					'function': 'heartbeat',
					IastID: lastmsgid()
				 },
			dataType: "json",
			success: function(r){
				var h=[];
				var g=[];

				var z = r;
				//g.push(channel);
				for(var t=0;t<z.length;t++)
				{
					addChatLine(z[t]);
				}
				//alert(z.data.chats.length);
				if(z.length){
					noActivity = 0;
					nextRequest = 4000;
				}
			},
		});
			
		if(noActivity > 3){
			nextRequest = 5000;
		}
		
		if(noActivity > 10){
			nextRequest = 10000;
		}
		
		// 15 seconds
		if(noActivity > 20){
			nextRequest = 15000;
		}
		$('#activity').html('<p class="noChats">No chats yet '+noActivity+' hb time '+nextRequest+'</p>');
		setTimeout(updateChat,nextRequest);

	}
	
	function render(template,params){
		
		var arr = [];
		switch(template){
			case 'loginTopBar':
				arr = [
				'<span><img src="',params.gravatar,'" width="23" height="23" />',
				'<span class="name">',params.name,
				'</span><a href="" class="logoutButton rounded">Logout</a></span>'];
			break;
			case 'chatLine':
				arr = ['<div class="chat" id="chat-',params.id,'" style="color: ',color[params.level],'!important;"><span class="author">',params.userName,
					' : </span><span class="text">',params.text,'</span></div>'];

			break;
			
			case 'user':
				arr = [
					'<div class="user" title="',params.name,'"><img src="',
					params.gravatar,'" width="30" height="30" onload="this.style.visibility=\'visible\'" /></div>'
				];
			break;
		}
		// A single array join is faster than
		// multiple concatenations
		return arr.join('');
	}
	
	function addChatLine(params){

		// All times are displayed in the user's timezone
		var d = new Date();
		if(params.time) {	
			// PHP returns the time in UTC (GMT). We use it to feed the date
			// object and later output it in the user's timezone. JavaScript
			// internally converts it for us.
			d.setUTCHours(params.time.hours,params.time.minutes);
		}
		
		params.time = (d.getHours() < 10 ? '0' : '' ) + d.getHours()+':'+
					  (d.getMinutes() < 10 ? '0':'') + d.getMinutes();
		
		var markup = render('chatLine',params),
			exists = $('#chat-'+params.id);

		if(exists.length){
			exists.remove();
		}
		
		if(!IastID){
			// If this is the first chat, remove the
			// paragraph saying there aren't any:
			$('.noChats').remove();
		}
		
		// If this isn't a temporary chat:
		if(params.id.toString().charAt(0) != 't'){
			$('#chatroom').append(markup);
		}
		var sHeight = $('#chatroom')[0].scrollHeight;
		$('#chatroom').scrollTop(sHeight);
		
	}
	
	function lastmsgid()
	{
		getID =  $('#chatroom').children('div').last().attr('id');//.replace('chat-','');
		if (getID)
		{
			myarr = getID.split("-");
			myvar = myarr[1];
			IastID 		= myvar;
		}
		else
		{
			IastID 		= 0;
		}
	
		return IastID;
	}
	
});

this is prity simple and has more features then you would want at the start thi s this uses timestamps avatars and usernames when chatting

 

the html

<div id="content" style="display: block;">

	<div id="chatroom" class="chatrm">
	</div>
	
	<div id="inputFieldContainer" class="inputbar">
		<textarea id="inputField" class="mchatboxtextarea" title="Press SHIFT+ENTER to input a line break"></textarea>
	</div>
	
</div>

all the hard work is done by jquery so basic html the heartbeat checks the database for new messages the input sends the data to the processing page

 

witch is like this...

$function = $_POST['function'];

	switch ($function)
	{
		case 'heartbeat':
			$response = heartbeat();
		break;
		
		case 'send':
			$response = add_message($_POST);
		break;
	}
	
echo json_encode($response);

function add_message($post)
{
	global $roster, $addon;
	
	$sql = "INSERT INTO `".$roster->db->table('messages',$addon['basename'])."` ".
	"(`id`, `userID`, `userName`, `level`, `text`) VALUES ".
	"(NULL, '".$post['userID']."', '".$post['userName']."', '".$post['level']."', '".$post['text']."');";
	$result = $roster->db->query( $sql );
	if ($result)
	{
		return array('status' => true);
	}
	else
	{
		return array('status' => false,'sql' => $sql);
	}
}
function heartbeat()
{	
	global $roster, $addon;
	
	$sql = "Select * FROM `".$roster->db->table('messages',$addon['basename'])."`";
	$result = $roster->db->query( $sql );
	$mes = array();
	while($d = $roster->db->fetch($result))
	{
		$mes[] =  $d;
	}
	
	return $mes;
}

and thats all there is to my app really i hope this helps a lil

 

here is the guide it was based off of

http://css-tricks.com/jquery-php-chat/

  • Like 1

What's the linkup code for the jquery script, because I'd rather have it run as an auto update?

 

You will save me many more headaches now that I can see what I'm doing with the DB stuff, but will need to rewrite everything else around it now.

 

Can you post the table creation SQL, so I can see what your chat table looks like?

Edited by Q695
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `userID` int(11) NOT NULL,
  `userName` varchar(64) COLLATE utf8_bin NOT NULL,
  `level` varchar(64) COLLATE utf8_bin NOT NULL,
  `dateTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `text` text COLLATE utf8_bin,
 PRIMARY KEY (`id`)");

thats the table structure there is also a js part thats inserted to the header of the page for the use

<script type=\'text/javascript\'>
/* <![CDATA[ */
var wr = {"userID":"'.$id.'","userName":"'.$name.'","level":"'.$level.'"
};
/* ]]> */
</script>

this script auto polls the db to the request file index.php?send=true but i would recommend using a script file then the index to do this but the link for the example this was based off is a much easier way to get started

  • Like 1
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.