Jump to content

Chat box and IM system


shadowayex

Recommended Posts

Hello. I'm currently developing a website for a local club and they were interested in having an IM system and possibly a chatroom. I've seen chat rooms on PHP pages before, although I don't know if they were actually built out of PHP. And I have no clue about an IM system. Can someone help me out or point me in the right direction so I can fine someone to help me out. Thanks to anyone who can.

Link to comment
Share on other sites

  • Replies 76
  • Created
  • Last Reply

You will need PHP, and if you want it to be smooth JavaScript using AJAX. Basically, you have PHP pages that do all the work (interact with the database to add and display messages), which are called by your page through AJAX.A chatroom is easier than an IM system as you don't have to worry to such an extent about permissions.

Link to comment
Share on other sites

Ok, I've been working and I know how to do a basic chat deal in PHP. But with the one I have, people have to hit refresh to see new posts, like a forum. How to I make it automated? I know the basics of AJAX and I've got a good bit of experience with PHP/MySQL and JS.

Link to comment
Share on other sites

But with the one I have, people have to hit refresh to see new posts, like a forum. How to I make it automated?
You make a recursive JS function (through setInterval() or setTimeout()) that uses AJAX to call the page that returns the past messages, then displays them.
Link to comment
Share on other sites

Um, not sure how to do that. I tried testing the setInterval() function and got no results. How do I set it up so the results show up in a <div>. I tried:setInterval(test(),50)var try=1;function test(){ try=try+1; document.getElementById("test").innerHTML=try;}And placing <div id="test"></div> in the body section and got nothing.

Link to comment
Share on other sites

You have to put the first arguement of setInterval() in quotation marks.

setInterval("test()",50)

By the way, you can cheat and put

function test() {	document.getElementById("test").innerHTML = ++try;}

Link to comment
Share on other sites

chatroom.php

<?php session_start();$link = mysql_connect('host', 'user', 'password')    or die('Could not connect: ' . mysql_error());mysql_select_db('database') or die('Could not select database');$user=$_SESSION['user'];$message=mysql_real_escape_string($_POST['message']);if($message!=""){mysql_query("INSERT INTO chat (Username, Message) VALUES ('$user', '$message')");}$result = mysql_query("SELECT * FROM chat");while($row = mysql_fetch_array($result)) { echo "{$row['Username']} : {$row['Message']}"; echo "<br />"; }mysql_close($link);?><html><head><title>Test Chat</title><script type="text/javascript" src="chat.js"></script><script type="text/javascript">setInterval("test()",50)var try=1;function test(){try=try+1;document.getElementById("test").innerHTML=try;}</script></head><body><div id="txtHint"></div><form action="chatroom.php" method="post"><input type="text" name="message" value="" /><input type="submit" name="submit" value="Send" /></form><div id="test"></div></body></html>

And just in case you need it.chat.js

var xmlHttpfunction showUser(str){ xmlHttp=GetXmlHttpObject()if (xmlHttp==null) { alert ("Browser does not support HTTP Request") return }var url="chatroom.php"xmlHttp.onreadystatechange=stateChanged xmlHttp.open("POST",url,true)xmlHttp.send(null)}function stateChanged() { if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {  document.getElementById("txtHint").innerHTML=xmlHttp.responseText  } }function GetXmlHttpObject(){var xmlHttp=null;try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); }catch (e) { //Internet Explorer try  {  xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");  } catch (e)  {  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");  } }return xmlHttp;}

As you probably can see, eventually it's the AJAX functions I was to get to repeat. But after failing with them I decided to start small.

Link to comment
Share on other sites

I would suggest separating your pages into chatroom.php (the one the user goes to) and chat_process.php (the one which the AJAX script calls). Then it will be much less confusing. I have to go now, but try that, I (or someone else) will have a look at your script a bit later.

Link to comment
Share on other sites

So I split it up like you said and now it won't show messages at all. The part of the code that the AJAX function deals with is:$result = mysql_query("SELECT * FROM chat");while($row = mysql_fetch_array($result)) { echo "{$row['Username']} : {$row['Message']}"; echo "<br />"; }And this bit is for sending the messages:$message=mysql_real_escape_string($_POST['message']);if($message!=""){mysql_query("INSERT INTO chat (Username, Message) VALUES ('$user', '$message')");}When it's all on the same page, it works just fine. I just can't seem to get the setInterval to work, even on simple little tests I can't get it to work.

Link to comment
Share on other sites

Don't forget to include the database connection script in all your pages. Lets put it in a file called connect.php.chat_get_messages.php

include("connect.php");$result = mysql_query("SELECT * FROM chat");while($row = mysql_fetch_array($result)){echo "{$row['Username']} : {$row['Message']}";echo "<br />";}

chat_send_message.php

include("connect.php");$message=mysql_real_escape_string($_POST['message']);$user = $_SESSION['user'];if($message!=""){mysql_query("INSERT INTO chat (Username, Message) VALUES ('$user', '$message')");}echo file_get_contents("chat_get_messages.php");

chatroom.php

<script type="text/javascript">var getHttp;var postHttp;getHttp = new XMLHttpRequestObject(); //Include IE lte 6 connect too latergetHttp.onreadystatechange = function() {	if (getHttp.readyState == 4) document.getElementById("message").innerHTML = getHttp.responseText;}postHttp = new XMLHttpRequestObject(); //Include IE lte 6 connect too laterpostHttp.onreadystatechange = function() {	//You want the message box to be instantly updated when they post. Lag less	if (postHttp.readyState == 4) document.getElementById("message").innerHTML = postHttp.responseText;}function get_messages() {	getHttp.open("GET","chat_get_messages.php");	xmlHttp.send(null);}function send_message() {	sendHttp.open("POST", "chat_send_message.php");	sendHttp.setRequestHeader("content-type", "application/x-form-urlencoded");	data = "message=" + document.getElementById("input").value;	sendHttp.setRequestHeader("content-length", data.length);	sendHttp.send(data);	return false;}window.onload = function() {	setInterval("get_messages()", 1000);}</script><!-- ... --><div id="message"></div><form onsubmit="return send_message()"><input type="text" style="width:300px; " id="input" /><input type="submit" value="Send Message" /></form>

That should work... bar syntax errors.

Link to comment
Share on other sites

hi, what browser are you using, the code have this object:--> postHttp = new XMLHttpRequestObject(); //Include IE lte 6 connect too later <--so you might be not getting the object with your browseri currently use this, it's from the php tutorial in w3schools

try	{		// Firefox, Opera 8.0+, Safari		xmlHttp=new XMLHttpRequest();	}	catch (e)	{		//Internet Explorer		try		{			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");		}		catch (e)		{			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");		}	}

it have worked splendid everywhere i use it

Link to comment
Share on other sites

For a more multi-browser XMLHttpRequest you could do

xmlHttp = (window.XMLHttpRequest) ? new XMLHttpRequest : new ActiveXObject("Microsoft.XMLHTTP");

This clears the overhead of try ... catch. But try DD's, it may work better than mine as I have had no time to test mine out. E.g. I just noticed I typed xmlHttp.send(null); in the get_messages() function - its supposed to be getHttp.send(null);

Link to comment
Share on other sites

I don't know if this has something to do, but I think that you need to call your function recursively.Take, this for example:

function getMessages(){	var ajax=null;				ajax=GetXmlHttpObject();	if (ajax==null)		return alert ("Your browser doesn't support AJAX");			var url="getmessage.php?mode=read";	ajax.onreadystatechange=function()	{		if (ajax.readyState==4)		{				if (ajax.responseText!="No message")				document.getElementById("chat").innerHTML+=" "+ajax.responseText;			document.getElementById("chat").scrollTop=document.getElementById("chat").scrollHeight;		}	}	ajax.open("GET",url,true);	ajax.send(null);	setTimeout("getMessages()",1000);}

That's the main code of a chat I made a month ago using AJAX, and it works perfectly.

Link to comment
Share on other sites

I don't really know how Synook's code work (too lazy to analyze), but here's my code:

function sendMessage(){	ajax=null;	ajax=GetXmlHttpObject();	if (ajax==null)		return alert ("Your browser doesn't suppor AJAX");		var message=new String(document.getElementById("message").value);		message=message.split("\n").join("<br>");	var url="getmessage.php?mode=send";	ajax.onreadystatechange=stateChanged;	ajax.open("POST",url,true);	ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");		var param="message="+encodeURIComponent(message);	ajax.send(param);	document.getElementById("message").value="";	document.getElementById("message").focus();}

Here's getmessage.php:

include ("clases/bd.php");include ("clases/usuario.php");include ("clases/administrar_usuario.php");include ("clases/mensaje.php");include ("clases/administrar_mensaje.php");header("Cache-Control: no-store, no-cache, must-revalidate");session_start();		$basedatos=new BaseDatos("server","db_user","pass","db_name");$admin_mensaje=new AdministrarMensaje($basedatos);if (!isset($_SESSION['ultimo']))	$_SESSION['ultimo']=$admin_mensaje->getUltimoID();	if ($_GET['mode']=="send"){	$texto_mensaje=$_POST['mensaje'];		$mensaje=new Mensaje($texto_mensaje,$_SESSION['usuario']);	$admin_mensaje->publicar($mensaje);}elseif ($_GET['mode']=="read"){	$id=$admin_mensaje->getUltimoID();	if ($id!=$_SESSION['ultimo'])	{				$mensajes=$admin_mensaje->getMensajes("*","id>".(int)$_SESSION['ultimo']);		for ($i=0;$i<count($mensajes);$i++)			echo "<b>".$mensajes[$i]->getUsuario()->getNick()." dice:</b> ".$mensajes[$i]->getTexto()."<br>";		$_SESSION['ultimo']=$id;	}	else		echo "No message";}	$basedatos->desconectar();?>

This PHP code is simple (ignore the var names in Spanish):I get the mode for which the page is accessed; if the mode is "read", I get the last message ($admin_mensaje is a class, and getUltimoID() is the method where I get the last message ID); the last message ID is also stored in a session var called $_SESSION['ultimo'], then I compare them. If the value I just got through the class is different than the value stored in the session var, would mean that there's a new message, so I show all the messages whose ID are greater than session's value, and the session var is updated with the value I just got with $id.If the mode is "send", well, I make all the operations to register the message in the DB.Hope that helps. If you have any question, don't be afraid to ask.

Link to comment
Share on other sites

More errors in my code if you are still using it: in my send_message() function I use sendHttp - its supposed to be postHttp.

Link to comment
Share on other sites

Yeah I'm still using your code Synook. I think it will work now, but I'm having a hard time connecting to my site right now so I can't test it >_<. But if I wanted to add a field or two to the database, would that change the AJAX? Or could I just add it to the PHP. The fields have nothing to do with what's displayed. I want to see if I can make it so the user could choose a specific username for the message to only be displayed to.EDIT: I changed all the sendHttp to postHttp in the send_message() thing and it still didn't send the message, and then it wouldn't show the messages already in the database. Then I changed them back to sendHttp and it showed the messages again, but still no sending.SECOND EDIT: After more testing, I found out that I could change this:

function send_message() {	sendHttp.open("POST", "chat_send_messages.php");	sendHttp.setRequestHeader("content-type", "application/x-form-urlencoded");	data = "message=" + document.getElementById("input").value;	sendHttp.setRequestHeader("content-length", data.length);	sendHttp.send(data);	return false;}

To this:

function send_message() {	postHttp.open("POST", "chat_send_messages.php");	postHttp.setRequestHeader("content-type", "application/x-form-urlencoded");	data = "message=" + document.getElementById("input").value;	postHttp.setRequestHeader("content-length", data.length);	sendHttp.send(data);	return false;}

Without problem (it still won't send messages though). But if I try to change sendHttp.send(data); to postHttp.send(data); it will show the messages just fine, until I try to send something. After that, it just shows a line of empty text. I'm going to screw with it more, but if someone has a solution, by all means please let me know. I also discovered if I add a message to the database through phpmyadmin (I did this to test the auto refresh deal), it won't auto refresh. I don't know if the auto refresh will work if I submit through the form you built because it doesn't submit >_<. Also, I looked through your code. I wasn't sure what a lot of it was really doing because it looks much different that what I was using, but I was assuming that when you hit submit, it was supposed to do the send_message() function. I'm sure that's what it's doing because of the sendHttp.send(data) issue. Looking through that, I assume that this line:data = "message=" + document.getElementById("input").value;In the function is what is supposed to tell the PHP what to write in the database. If that is the case, should "message=" be "$message=" to set a PHP variable? (I assume this, I might be completely wrong) And if that's the case, shouldn't I remove the line setting the $message variable in the chat_send_messages.php file? I'd test this, but I don't know what's going on with the chat itself when I click submit with the postHttp.send(data) thing.To explain that issue a little more. When the page loads, the messages load just fine. But when I type in, oh let's say "Hi", when I type in "Hi" and submit it, the messages dissapear, an empty line appears, and the word "Hi" still stays in the text input.Also, I was wondering if I can have the messages put into a textarea?

Link to comment
Share on other sites

In the function is what is supposed to tell the PHP what to write in the database. If that is the case, should "message=" be "$message=" to set a PHP variable?
No - the data is x-form-urlencoded, which is like querystring format.
Also, I was wondering if I can have the messages put into a textarea?
Why? You can format a division with definite height, and even make the font monospace if your really want to.
To explain that issue a little more. When the page loads, the messages load just fine. But when I type in, oh let's say "Hi", when I type in "Hi" and submit it, the messages dissapear, an empty line appears, and the word "Hi" still stays in the text input.
The readystatechange handler of postHttp replaces the messages with the response of send_message.php. That page is supposed to echo the messages but there may be something wrong. Try copying the code of get_messages.php into send_message.php instead of having the file_get_contents().For getting rid of "Hi", in function send_message() add a new line:
document.getElementById("input").value = "";

Gtg now :)

Link to comment
Share on other sites

Ah, You see I don't know about the definite height of div type of stuff. Never had it shown to me, and didn't know it could be done. Does it put a scroll bar when the information gets to make more lines than what the div is defined to hold? If so, how do I do that?I did what you told me to. It still doesn't work. I even added the code to clear the input text box. It doesn't clear. It must be something wrong with the send_message() function.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.


×
×
  • Create New...