ASP 101 - Active Server Pages 101 - Web05
The Place ASP Developers Go!

Please visit our partners

Windows Technology Windows Technology
15 Seconds
ASP 101
ASP Wire
VB Forums
VB Wire
internet.commerce internet.commerce
Partners & Affiliates

ASP 101 is an site
ASP 101 is an site
Internet News
Small Business
Personal Technology

Corporate Info
Tech Jobs
E-mail Offers

ASP 101 News Flash ASP 101 News Flash

 Top ASP 101 Stories Top ASP 101 Stories
An Overview of ASP.NET
Connections, Commands, And Procedures
What is ASP?

Create Database Tables From ASP
Show All Tips >>
ASP 101 RSS Feed ASP 101 Updates

Chat Using ASP & XML

by Mohamed Najeeb


This article assumes that you are familiar with ASP, XML and HTML.

Using this chat system, we can chat how we conventionally chat, in public as well as private modes. Even though I've implemented most of the conventional features such as unique nick names, the reader is welcome to incorporate any other features they require. Please note that I didn't worry much about memory usage on the server side and the code that allots user ids obviously needs improvement.

Let us talk about the overall functionality. The message from the browser is sent to the server via Microsoft's XMLHTTP Object. Using this same XMLHTTP Object, the messages are retrieved from the server and displayed on the page. The users list comes from the server along with messages. It is currently configured so that the browser requests the current users list from the server every 5 seconds.

How it works

The following screens are identical to the chat system.

Your Nick Name:

User: Najeeb Logout
Public Private

Once a user logs into the chat system, that user is given a unique userid, an integer stored in the chat page, and their user name is stored in the ASP Application object.

A message from any browser is stored in the server in such a way that if the mode of the message is private then the message is stored in the application object against each user in the private user list which comes along the message and if public mode then message is stored for each user available in the application object.

In the user page messages, as well as the user list, get updated in two ways. First, if a user sends any message to the server by clicking the 'Send' button, then any messages in this user's account and the current user list (available in the server side application object) are sent to the browser. Second, the timer event set in the page to run every 5 seconds accomplishes the same thing.

The following files are used in the chat system.

Login.asp :

Response.Expires = 0
'if this page is requested by clicking the Submit button
if request("submit") <> "" then
  dim count,user,strMsg
  user = Request.form("txtUser")
  'check for white space
  if instr(user," ") > 0 then
      strMsg = "space is not allowed, please"
  end if
  'get the total no. of online users
  count = cint(Application("usercount"))
  'check for duplicate name
  for i = 1 to count
     if trim(user) = application("name" & i) then
        strMsg = "Please enter another Nick name"
     end if
  'if everything is OK,
  'then store the user name in the application object as well as
  'the session object, increment the user count by one, and
  'open the chat window
  if strMsg = "" then
    count = count + 1
	Application("usercount") =  count
	Application("name" & count) = user
	session("user") = user
	Response.Write "<script>" & _""chat.html?userid=count & "Name*" & user & _
	""","""",""toolbar=no,location=no,directories=no," & _
	"status=no,menubar=no,resizable=no,scrollbars=no," & _
 end if
end if
<title>C H A T </title>
    //to maintain a standard in names,
    //name entered by the user is changed to lowercase
    //except the first character which is to uppercase.
    function changeCase(){
        var strName;
        var data = document.frm.txtUser.value;
        strName = data.substr(0,1).toUpperCase();
        strName += data.substr(1).toLowerCase();
        document.frm.txtUser.value = strName;
<body onload="document.frm.txtUser.focus();">
<form name=frm action="login.asp" method="post" onsubmit="changeCase()">
<table border=1 width=50% bgcolor=DarkSeaGreen align=center>
<tr><td align=center>
<font color=darkblue size=7>C H A T</font><br>
<font color=red><%= strMsg %></font>
Your Nick Name:
	<input size=15 name=txtUser>
	<input type=submit value="Submit" name=submit>

Chat.asp :

Response.Expires = 0
dim strXML,msgXML,usersXML,userList,user,apname,msg,count
'strXML - a string to store the entire xml document ' which is sent to the browser. 'msgXML - a string to store the message content. ' It is a part of the strXML. 'usersXML - a string to store the users content. ' It is a part of the strXML. 'userList - a string array to store the users' names ' coming from the client (browser) to whom ' the message from the client should be sent. 'user - name of the user stored in the session object. 'apname - the user name stored in the application object. 'msg - the message coming from the client. 'count - used as counting index 'populate the user array for private message userList = split(request("userList"),"-") user = session("user") msg = request("Msg") Application.Lock 'add msg to the Message Queue if trim(msg) <> "" then if request("userList") <> "" then 'private msg for i = 0 to ubound(userList) count = cint(application(userList(i) & "_count")) + 1 application(userList(i) & "_msg_from_" & count) = user application(userList(i) & "_msg_" & count) = msg application(userList(i) & "_count") = count next else 'public msg to all for i = 1 to cint(application("usercount")) apname = application("name" & i) if application( apname & "_count") <> "" then count = cint(application( apname & "_count")) else count = 0 end if if apname <> "" AND trim(apname) <> trim(user) then count = count + 1 application(apname & "_msg_from_" & count) = user application(apname & "_msg_" & count) = msg application(apname & "_count") = count end if next end if end if 'get messages to this user, 'store them in msgXML, and 'after storing the messages delete them 'from the application object. if application(user & "_count") <> "" then for i = 1 to cint(application(user & "_count")) msgXML = msgXML & "<msg><from>" & _ "application(user & "_msg_from_" & i) & _ "</from><dat>" & _ application(user & "_msg_" & i) & _ "</dat></msg>" application(user & "_msg_from_" & i) = "" application(user & "_msg_" & i) = "" next application(user & "_count") = 0 end if 'get all the online user names 'in the application object, and store them in usersXML if application("usercount") <> "" then usersXML = "<users>" for i = 1 to cint(Application("usercount")) if Application("name" & i) <> "" then usersXML = usersXML & "<name>" & _ Application("name" & i) & "</name>" end if next usersXML = usersXML & "</users>" end if 'make the full XML content as follow. strXML = "<chat>" & usersXML & msgXML & "</chat>" 'send the XML content to the client. response.write(strXML) Application.UnLock

Chat.html :

<title>C H A T</title>
   //hLoc - to parse the username and the userid
   var hLoc = document.location.href;
   //to manage the xml document
   var objDOM = new
   //to establish a http connection between the
   //and the client, thereby sending and
   //message to and from the server
   //without submitting the page
   var xmlh = new
   //to store the user name
   var userName = '';
   //to identify whether the server is contacted
   //by clicking the send button OR
   //the routine timer event
   var isBtnPressed = false;
   //to display the incoming messages
   function listMsg() {
	var nodes,strTxt;
	 nodes = objDOM.getElementsByTagName("msg");
	 strTxt = '';
	if (document.frm.MsgScreen.innerText != '')
	    strTxt = document.frm.MsgScreen.innerText;
		strTxt += '\n' + nodes.item(i).firstChild.text +
		     ' >>' + nodes.item(i).lastChild.text  ;
  	    document.frm.MsgScreen.innerText = strTxt;
   //to display the incoming user list
   function listUser() {
      var nodes,strHtml;
      var selList = new
      var newList = new
      nodes = objDOM.getElementsByTagName("name");
      //getting the selected users
              selList[j++] = document.frm.usrList.options[i].text;
      //getting the current user list
          newList[i] = nodes.item(i).text;
      //updating the user list in the page
          document.frm.usrList.options[i] = new
      //removing the excess users in the page if
          document.frm.usrList.options[i] = null;
      //selecting the users in this updated user
      for(i=0;i<document.frm.usrList.length;i++) {
          for(j=0;j<selList.length;j++) {
                  document.frm.usrList.options[i].selected =true ;
   //to configure the initial settings
   function init()  {
	var index1,index2,index3;
        index1 = hLoc.indexOf("=")+1;
	index2 = hLoc.indexOf("Name");
	index3 = hLoc.indexOf("*");
	document.all("userid").value =
	userName = hLoc.substr(index3+1)
	user.innerHTML = "<b>User: <font color=RoyalBlue>" +
 		         userName + "</font></b>";
	sendMsg('joined the room');
	id = setInterval("requestMsg()",5000);
    //to do some housekeeping before and after sending
the msg 
    //to the server
    function sendMsg(data) {
	isBtnPressed = true;
	if (data != '')
	    document.frm.msgData.value = data;
	 if (document.frm.msgData.value != ''){
	      document.frm.MsgScreen.innerText =
                      document.frm.MsgScreen.innerText +
                      '\n' + userName + ' >>' +
                      document.frm.msgData.value ;
	      document.frm.msgData.value = '';
	  isBtnPressed = false;
    //to send the msg entered to the server
    function requestMsg() {
	var data,userList;
	//get the selected users if message type is
	userList = '';
	if (document.frm.msgType[1].checked == true){
                  userList +=
                       document.frm.usrList.options[i].text + '-';
	if (isBtnPressed == true)
	    data = document.all("msgData").value;
	    data = '';"POST","chat.asp?Msg=" + data + "&UserList;=" +
	Chatdata.documentElement = objDOM.documentElement;
   function logout(){
     	sendMsg('left the room.');
<xml id="Chatdata"><chat></chat></xml>
<body onload="init()"
<form name=frm method=post action="logout.asp"
				onsubmit="return false;">
<input type=hidden
name=userid value=''>
<table border=0 align=center width=60%>
align=right><A href="javascript:logout();">Logout</a>
  <tr><td><textarea name=MsgScreen cols=50 rows=10 readonly>
               Welcome to the CHAT System</textarea>
       <td align=right><div id="list">
          <select name=usrList multiple size=10 style="width:150">
     <input name=msgData size=58 value=''>
     <input type=button name=Submit value=Send
    <td align=center><input type=radio name=msgType
                             value="Pub" checked>
    <font color=white><b>Public
	<input type=radio name=msgType value="Pri">Private</b>

Logout.asp :

dim user Response.Expires = 0 user = Application("name" & request("userid")) Application("name" & request("userid")) = "" session.abandon if application(user & "_count") <> "" then for i = 1 to cint(application( user & "_count")) application(user & "_msg_from_" & i) = "" application(user & "_msg_" & i) = "" next end if application(user & "_count") = ""
<script> self.close(); window.opener.document.location.href = "login.asp"; window.opener.focus(); </script>

Area of Improvements

The reader could concentrate to enhance the flexibility and features of the chat system particularly on the following areas.
  • Memory management in UserID allotment operation
  • Validation of special characters in user's name

Home |  News |  Samples |  Articles |  Lessons |  Resources |  Forum |  Links |  Search |  Feedback
The Network for Technology Professionals



Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | E-mail Offers