Page 1 of 1

jQuery chat / shout box

Posted: Fri Aug 05, 2011 9:47 pm
by Torniquet
Hey guys,

A one off from the white label game series.

http://www.youtube.com/user/GetTaptIn#g ... E8E70F2B1D

jQuery chat/shout box which can be used for any site. Also uses abit of jSON :) (I know jSON isnt needed for this, but it still teaches you abit about its use)


Source code as requested :)

Chat.html

Code: Select all

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function send_shout()
{
	var username = $('.js_username').val();
	var message = $('.js_message').val();
	
	$.post("chat.php", {mode : 'send-shout', user : username, shout : message});
	
	$('.js_message').val('');

}

function update_shout()
{
	var timestamp = $('.js_shouts .js_shout_hold:first-child input[type="hidden"]').val();
	var json = "";
	var formdata = "";
	
	$.ajax({
		
		type: "post",
		url: "chat.php",
		data: {mode : 'check-update'},
		success: function(msg){
			if(msg > timestamp)
			{
				
				var formdata = "mode=update-shout&timestamp=" + timestamp;
				
				$.getJSON("chat.php", formdata, function(json){
					
					$.each(json, function(key, value)
					{
						var output = '<div class="js_shout_hold"><input type="hidden" value="' + value.timestamp + '" />' + value.user + ' says: ' + value.message + '</div>';
						$('.js_shouts').prepend(output);
					});
					
				});
				
			}
			
		}
		
	});
	
}
</script>
</head>

<body onload="setInterval('update_shout()',1000)">
<p>
	Username: <input type="text" name="username" class="js_username" />
</p>
<p>
	Message: <input type="text" name="message" class="js_message" size="80" maxlength="150" /> » <input onclick="send_shout();" type="submit" name="shout" class="js_shout" />
</p>
<div class="js_shouts" style="width: 600px; border:thin solid black; height: 150px; overflow-x: scroll">
	<div class="js_shout_hold"><input type="hidden" value="0" /></div>
</div>
</body>
</html>

Chat.php

Code: Select all

<?php

$connect = new mysqli('localhost', 'root', '', 'testing');

if($_POST['mode'] == "send-shout")
{
	$query = "INSERT INTO chat SET
				username = '{$_POST['user']}',
				message = '{$_POST['shout']}',
				timestamp = UNIX_TIMESTAMP(NOW())";
				
	$connect->query($query);
}
elseif($_POST['mode'] == "check-update")
{
	$query = "SELECT timestamp FROM chat ORDER BY timestamp DESC LIMIT 1";
	$sql = $connect->query($query);
	$row = $sql->fetch_object();
	
	echo $row->timestamp;
}
elseif($_GET['mode'] == "update-shout")
{
	$query = "SELECT * FROM chat WHERE timestamp > {$_GET['timestamp']}";
	
	$sql = $connect->query($query);
	
	while($row = $sql->fetch_object())
	{
		$data[] = array(
			"user"		=>	$row->username,
			"message"	=>	$row->message,
			"timestamp"	=>	$row->timestamp,
		);
	}
	
	echo json_encode($data);
	
}

$connect->close();
?>

Re: jQuery chat / shout box

Posted: Fri Aug 05, 2011 9:50 pm
by 62896dude
Torn... you rock! Hahaha, I don't have time right now to watch this, but this is going to be EXTREMELY useful! Thanks so much! :)

Re: jQuery chat / shout box

Posted: Fri Aug 05, 2011 10:30 pm
by Tim
You sir are my hero. Just skimmed around the four videos but I think this will provide exactly what I need. Going to work on this tomorrow when I have some more time.

Thanks!

Re: jQuery chat / shout box

Posted: Fri Aug 05, 2011 10:40 pm
by Xaleph
Yeah works nice, hmm about the trick to remove the scrolling, remove any and all overflows. If all is correct, it should scroll automatically. If not, try floating inner elements and use overflow: hidden, should force the container to scroll.

Also, you can easily add channels, add a fourth field to the table called channel and let users select a channel and submit stuff. On the jquery data retrieving, just filter away everything where channel != submitted channel. Or better: let PHP handle it.

Re: jQuery chat / shout box

Posted: Fri Aug 05, 2011 11:04 pm
by Torniquet
Xaleph wrote:Yeah works nice, hmm about the trick to remove the scrolling, remove any and all overflows. If all is correct, it should scroll automatically. If not, try floating inner elements and use overflow: hidden, should force the container to scroll.

Also, you can easily add channels, add a fourth field to the table called channel and let users select a channel and submit stuff. On the jquery data retrieving, just filter away everything where channel != submitted channel. Or better: let PHP handle it.

cheers xaleph for the scroll tip, i will look into this later.

on the channels note, my website used to (technically still does) have a magic wall for posting to the profile being viewed. worked the same way.

http://youtu.be/HuOdxeu4jWI

it sent over the users ID and posted to their wall and retrieved all from their wall only on the php side :) I didnt really want to overdo it for a general shout box.

Re: jQuery chat / shout box

Posted: Fri Aug 05, 2011 11:14 pm
by Xaleph
Works nice ! Yeah, I can imagine, besides, the tutorial was written for a shoutbox/ajax chat, you did just that, right?

Anyway, I just wanted to have it said because I can see why 62dude would want something like that ( am I right? ) , anyway, good job on the tutorials, did watch the first 2 movies, you teach it good :)

Re: jQuery chat / shout box

Posted: Fri Aug 05, 2011 11:37 pm
by 62896dude
Yep Xaleph, it goes perfectly with HPD's site

Re: jQuery chat / shout box

Posted: Sat Aug 06, 2011 1:08 am
by Nexus
Heh wonder who that friend is ;) thanks torn for clearing that up, my head was going to explode. :)

Re: jQuery chat / shout box

Posted: Sat Aug 06, 2011 2:42 am
by 62896dude
Hello Torniquet,

Here is my chat.html:

Code: Select all

<html>
<head>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function send_shout()
{
	var username = $('.js_username').val();
	var message = $('.js_message').val();
	
	$.post("chat.php", {mode : 'send-shout', user : username, shout : message});
	
	$('.js_message').val("");
	
}

function update_shout()
{
	var timestamp = $('.js_shouts .js_shout_hold:first-child input[type="hidden"]').val();

	$.ajax({
	
		type: "post",
		url: "chat.php",
		data: {mode : 'check-update'},
		success: function(msg){
			
			if(msg > timestamp)
			{

				var formdata = "mode=update-shout&timestamp=" + timestamp;
				
				$.getJSON("chat.php", formdata, function(json){
					
					$.each(json, function(key, value)
					{
						var output = '<div class="js_shout_hold"><input type="hidden" value="' + value.timestamp + '" />' + value.user + ' says: ' + value.message + '</div>';
						$('.js_shouts').prepend(output);
					})
					
				});
			
			}
			
		}
		
	});
	
}
</script>
</head>
<body onload="setInterval('update_shout()',1000)">

<p>

	Username: <input type="text" name="username" class="js_username" />

</p>
<p>

	Message: <input type="text" name="message" class="js_message" size="80" maxlength="250" /> » <input type="submit" name="shout" class="js_shout" />

</p>
<div class="js_shouts" style="width: 600px; border:thin solid white; height:150px; overflow-x: scroll">

	<div class="js_shout_hold"><input type="hidden" value="0" /></div>
</div>
</body>
</html>
Here is my chat.php:

Code: Select all

<?php

include_once('connect.php');
include_once('session.php');

if($_POST['mode'] == "send-shout")
{
	$query = "INSERT INTO chat SET
		username = '($_POST['username'])',
		message = '($_POST['shout'])',
		timestamp = UNIX_TIMESTAMP(NOW())";
		
}
elseif($_POST['mode'] == "check-update")
{
	$query = "SELECT timestamp FROM chat ORDER BY timestamp DESC LIMIT 1";
	$sql = $db->query($query);
	$row = $sql->fetch_object();
	
	echo $row->timestamp;
}
elseif($_GET['mode'] == "update-shout")
{
	$query = "SELECT * FROM chat WHERE timestamp > {$_GET['timestamp']}";

	$sql = $db->query($query);
	
	while($row = $sql->fetch_object())
	{
		$data[] = array(
			"user"		=>	$row->username,
			"message"	=>	$row->message,
			"timestamp"	=>	$row->timestamp,
		);
	}
	
	echo json_encode($data);
	
}
?>
For some reason, it doesn't post any messages, and when I click the submit button to enter the message into the chat, nothing happens (If you want to see what I am talking about, you can go to the "Chat With Friends" link at Hogwarts at the HPD website)

I'm sure that I did something wrong here, but I can't figure out what... (I changed the code slightly, but not much)

Also, $db is the same thing as what your $connect.php was, it is in the connect.php, which is included

Thanks so much!

Re: jQuery chat / shout box

Posted: Sat Aug 06, 2011 3:50 am
by 62896dude
Actually, nevermind, I went through the script and found a lot of errors. My webhost is currently down, but when it goes back up, I'll test it again and see what happens!

Again, really great tutorial, an excellent pace

EDIT: Torn, could you post the source code for the two scripts? No matter how many times I go through this, I can't seem to get it right, I wanna see where I am going wrong. Thanks!