I am trying to set up a sort of instant messaging system on a site I am creating. Users submit their messages which are then stored in a database. Other users looking at the page should then be able to see this message as soon as possible.

The only way I can make this work is using Ajax to send a request to search for any new messages every 2 seconds or so. Is there a better way of doing this? I just don't think this is very good as for the user's Internet usage and it is barely instant.

Thanks if anyone has any ideas...

Recommended Answers

All 9 Replies

I also trying this . But anyone can help me .

Anyone have any ideas?

I'm sure someone must know a more efficient method?

i am also trying to make a chat app using flash and php ...but i am facing different problem ...my users are out from flash and passing username through JavaScript they can chat...but i cant display online users in realtime ....
how are you displaying users...

Use jQuery .load() method to a PHP script? I use it to simulate frontend applications monitoring real time data from machinery. If anyone wants it i can post a bit of code up...

Hi benhowdle,

that is kind of how I'm doing it at the moment. But it just means I (or rather the user) have to keep on .load()ing the PHP script. Which means that after 10minutes you could have made hundreds, maybe a thousand load()s, and if you have a thousand people messaging it would just become very slow and the user ends up with a heap of XHR documents.

This is one method that does work, but there must be a better way, maybe. Like a way to send the information to the user when it is first available (which is impossible I know, but something similar), instead of them having to request information every second or so.

Thank you for the link ben.

I think I am getting closer to a better method.

Now the user sends one request, this request is held by the PHP script using the sleep() function until any new messages are found it then sends the messages back to the user if there are any. The only problem is that when this request is being held by PHP the user cannot send any more message for some reason..

I am only sending two requests... receive and send.

Any way here is my code (mostly) below if someone can help me fix this.

Javascript (using jQuery):

function send(message){//Send message
	if(message&&message!='\n'){//If there is a message
		$.post('send.php','m='+message+'&t='+topic,processSend);//Request post.php
	}
}

function processSend(data){//When send.php returns
	if(data!=1){//send.php returns 1 on success
		$('#send_error').html(data).slideDown();//Give error on failure
		setTimeout("$('#send_error').slideUp();",4000)
	}
}

function receive(){//Recieve new messages
	$.getJSON('receive.php','p='+prev+'&t='+topic,processReceive);//Request receive.php (p=the previous message user received)
}

function processReceive(data){//When receive.php returns
	if(data){//If there were new messages found
		$.each(data,function(message,messageInfo){
			//Basically just adds the messages to the page and set prev as previous message
		});
	}
	setTimeout("receive()",100);//receive() again in 0.1 seconds
}

send.php:

$message=trim($_POST[m]);//Get message posted
$topic=$_POST[t];//Get topic posted
if($message&&$topic){
	$message=htmlspecialchars($message);//Remove HTML
	include "../inc/global.php";//This file connects to database (below)
	$sender=$_SESSION[username];
	if($sender){//If user is logged in
		$time=time();
		mysql_query("INSERT INTO messages(topic,sender,message,time) VALUES('$topic','$sender','$message','$time')")or die(mysql_error());//Insert message into database
		echo 1;//Success
	} else{
		echo 'error';
	}
} else{
	echo 'error';
}

receive.php:

include "../inc/global.php";//Connects to database (shown below)
$prev=$_GET[k];//Get ID of previous message received
$topic=$_GET[t];//Get topic

if($prev&&$topic){	
	for($x=0;$x<10&&$newMessagesQuery=mysql_query("SELECT * FROM messages WHERE id>'$prev' AND topic='$topic'");$x++){//Loop no more than 10 times, each time setting $newMessagesQuery as a query for new messages
		if(mysql_num_rows($newMessagesQuery)){//If message(s) were found
			$nMs=array();//New Messages
			while($message=mysql_fetch_assoc($newMessagesQuery)){//Write JSON for each message
				$nMs['m'.$message['id']]['id']=$message['id'];
				$nMs['m'.$message['id']]['sender']=$message['sender'];
				$nMs['m'.$message['id']]['message']=$message['message'];
				$nMs['m'.$message['id']]['time']=$message['time'];
			}
			echo json_encode($nMs);//Output JSON
			break;//Stop loop
		} else{
			sleep(1);//If no new messages were found then sleep for 1 second and check again...
		}
	}
	if($x==10){
		echo 0;
	}
} else{
	echo 0;
}

global.php:

$connection=mysql_pconnect("mywebhost.com","avario","******") or die("Could not connect to server.");//Connect to database
mysql_select_db("instantmessenger",$connection) or die("Could not locate database");
session_start();//Start Session

Please note that I have excluded a lot of code that I don't think is important and many names I use in the code above are not really the names I use.

I think the problem is server side. It would seem that I can't request a page from my host until the previous page has returned. I can't load another page on the site (which is unrelated) while I am requesting, I have to wait for the request to return.

Is there a setting I could change that would allow me to request 2 pages simultaneously without having to wait for the first one to return?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.