Click here to Skip to main content
15,357,967 members
Articles / Web Development / ASP.NET
Posted 7 May 2010


66 bookmarked

Chat Application in ASP.NET Using AJAX (Pop-up Windows)

Rate me:
Please Sign up or sign in to vote.
4.83/5 (28 votes)
7 May 2010CPOL3 min read
Chat application in ASP.NET using AJAX and SQL Server.


In this post, I want to share my work on developing a chat application that can be used with your regular ASP.NET applications. I am using AJAX, and SQL Server for the backend. This can only be used in ASP.NET 2.0 or higher as I am using the UpdatePanel.

Using the code

The application works as follows:

  • List of online users are displayed.
  • Online users list can be loaded from the backend database, logging an entry when a user logs into the application. The user names will be displayed as hyperlinks, with a unique chat ID for each.

  • The current logged-in user will click on a user name to open a new chat window, and types a message.
  • On clicking a username, the OpenChatBox() function is called with the chat ID as the parameter. When the user types any message and clicks on the Send button, the message is sent to the server and stored to the database with the chat ID supplied.

    function OpenChatBox(uid, chatid) {
        var win ="ChatBox.aspx?uid=" + uid + "&cid=" + 
                  chatid, "ChatWindow" + chatid + 
                  "status=0,toolbar=0, menubar=0, width=450, height=550");
        top = top + 50;
        if (top > screen.availHeight - 550)
            top = 100;
        left = left + 50;
        if (left > screen.availWidth - 450)
            left = 100;
        win.moveTo(left, top);
        chats[chats.length] = win;
        return false;

    The message storing is implemented in ASP.NET.

    Private Sub SendMessage(ByVal msg As String)
        Dim con As SqlConnection = New SqlConnection( _
                "Data Source=.\SQLEXPRESS;AttachDbFilename=" & _ 
                "D:\Dev\Projects\WebChat\WebChat\App_Data\WebChat" & _ 
                ".mdf;Integrated Security=True;User Instance=True")
        Dim comm As SqlCommand = New SqlCommand("stp_SendMessage", con)
        comm.CommandType = CommandType.StoredProcedure
        Dim paramSender As SqlParameter = New SqlParameter( _
            "@Sender", SqlDbType.VarChar, 10)
        paramSender.Value = HttpContext.Current.User.Identity.Name
        Dim paramRec As SqlParameter = New SqlParameter( _
            "@Reciever", SqlDbType.VarChar, 10)
        paramRec.Value = ViewState("uid")
        Dim paramMsg As SqlParameter = New SqlParameter( _
           "@Msg", SqlDbType.VarChar, 1000)
        paramMsg.Value = msg
        'store the chat id supplied from browser
        Dim paramChatId As SqlParameter = New SqlParameter( _
         "@ChatId", SqlDbType.VarChar, 100)
        paramChatId.Value = ViewState("vwChatId").ToString()
    End Sub


  • On the recipient's screen, a new pop-up window will appear.
  • One every user's home page, a script is run every 5 seconds to ping the server for any messages.

    function PingServer() {
        setTimeout(PingServer, 5000);
    function PingServerForMsg() {
           // Use ajax to call the GetChatMsg.aspx to get any new messages.
            xmlHttp = GetXmlHttpObject(stateChangeHandler);

    This JavaScript message will call the GetChatMsg.aspx page for new messages, and shown below is the code for GetChatMsg.aspx:

    Imports System.Data
    Imports System.Data.SqlClient
    Partial Public Class GetChatMsg
        Inherits System.Web.UI.Page
        Protected Sub Page_Load(ByVal sender As Object, _
                  ByVal e As System.EventArgs) Handles Me.Load
            'set response to not to cache, to avoid the ajax from displaying old message.
            Response.AddHeader("Cache-Control", "no-cache, must-revalidate")
            Dim ds As DataSet = GetMessage(HttpContext.Current.User.Identity.Name)
            Dim strMsg As String = ""
            If ds.Tables.Count > 0 Then
                If ds.Tables(0).Rows.Count > 0 Then
                    For Each dr As DataRow In ds.Tables(0).Rows
                        If strMsg.Length > 0 Then
                            strMsg += "#"
                        End If
                        strMsg += dr("Sender").ToString() + "&"
                        strMsg += dr("ChatId").ToString() + "&"
                        strMsg += dr("Msg").ToString().Replace("&", _
                                     "_@AMP__").Replace("#", "_@HASH__")
                End If
            End If
        End Sub
        Private Function GetMessage(ByVal strUid As String) As DataSet
            Dim dsMsgs As DataSet = New DataSet()
            Dim con As SqlConnection = New SqlConnection( _
                    "Data Source=.\SQLEXPRESS;AttachDbFilename=D:\Dev\" & _ 
                    "Projects\WebChat\WebChat\App_Data\WebChat.mdf;" & _ 
                    "Integrated Security=True;User Instance=True")
            Dim comm As SqlCommand = New SqlCommand("stp_GetMessage", con)
            comm.CommandType = CommandType.StoredProcedure
            Dim paramSender As SqlParameter = New SqlParameter( _
                "@Uid", SqlDbType.VarChar, 10)
            paramSender.Value = HttpContext.Current.User.Identity.Name
            If (Request.QueryString("cid") <> Nothing) Then
                Dim paramChatId As SqlParameter = New SqlParameter( _
                                 "@ChatId", SqlDbType.VarChar, 100)
                paramChatId.Value = Request.QueryString("cid")
            End If
            Dim da As SqlDataAdapter = New SqlDataAdapter(comm)
            Return dsMsgs
        End Function
    End Class

    On the browser side, on getting a new message, the browser will open a pop-up if the chat ID is new, or will show the message if a pop-up is already open for the chat ID associated with the new message.

    function stateChangeHandler() {
        //readyState of 4 or 'complete' represents that data has been returned 
        if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete') {
            //Gather the results from the callback 
            var str = xmlHttp.responseText;
            if (str != "" ) {
                //document.getElementById('txtMsg').value = str;
                var msgs = str.split('#');
                for (ind = 0; ind < msgs.length; ind++) {
                    msgs[ind] = msgs[ind].replace("_@HASH__", "#");
                    var msg = msgs[ind].split("&");
                    msg[0] = msg[0].replace("_@AMP__", "&");
                    msg[1] = msg[1].replace("_@AMP__", "&");
                    msg[2] = msg[2].replace("_@AMP__", "&");            
                    var blnExisting = false;
                    for (iind = 0; iind < chats.length; iind++) {
                            if (chats[iind] != null && chats[iind].name == 
                                "ChatWindow" + msg[1] + 
                            blnExisting = true;
                    if( blnExisting == false)
                        OpenChatBox(msg[0], msg[1]);
  • Users can communicate through the current window.
  • The recipient can type in a message to reply back using the same window. The pop-up window has the screen ChatBox.aspx, which has the ChatBox.js reference of the JavaScript code to ping the server again every second. But this time, it uses the chat ID assigned to that window. And thus, every chat has a unique chat ID, and chat messages are maintained at the backend by the chat ID, and the pop-up windows communicate through the chat ID. An UpdatePanel is used here to avoid flickering of the chat window when the user clicks Send Message. And when a message is received by the recipient, the message is deleted at the server.

  • A single user can communicate with multiple users at a time.
  • A user can chat with any number of users as pop-up windows are used for each chat with a unique chat ID for the chat. The chat ID is generated as 'Timestamp + Sender ID + Recipient ID'.

On clicking the Send button, the typed message will be saved by the code-behind to a table in SQL Server (here, any other database can be used). On the recipient side, on AJAX call, the message reader will read the messages related to the recipient and sent to the recipient. Please check the attached source code for the ASP.NET code, which is for Visual Studio 2008, but the same code can be used for VS 2005 (ASP.NET 2.0) without changes.

Image 2

When the first user sends a message, the message is saved to the backend for the selected user. When the application running on the recipient (implemented in default.aspx in the sample), AJAX is used to ping the server for messages every 5 seconds.

Image 3


  • Developers can try to implement saving the chat history.
  • The list of online users can be implemented in a user control to make it reusable.
  • Chat window can be changed to include the time of message and images.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Narsimlu Keshagouni
Technical Lead
India India
Hi, I am Narsimlu Keshagouni working as Technical Lead in Hyderabad, India.

Comments and Discussions

Questionquestion Pin
Member 137729188-Jun-18 5:18
MemberMember 137729188-Jun-18 5:18 
Questionnot able to attach your Webchat.mdf file in Sql Server 2012 Management studio Pin
Member 117976565-Aug-17 0:56
MemberMember 117976565-Aug-17 0:56 
GeneralMY VOTE OF 5 Pin
ch.nageshkumar20-Jun-14 1:09
Memberch.nageshkumar20-Jun-14 1:09 
QuestionWhere is the delete code in your attached code. Pin
VICK17-Dec-13 20:08
professional VICK17-Dec-13 20:08 
Questioncommunicate with each other Pin
sandeepkumarvemula30-Oct-13 19:39
Membersandeepkumarvemula30-Oct-13 19:39 
Generalthz Pin
balasekar.v9-May-13 19:11
Memberbalasekar.v9-May-13 19:11 
GeneralMy vote of 4 Pin
kasheer4-May-13 19:26
Memberkasheer4-May-13 19:26 
Bugerror while executing Pin
nive28073-Mar-13 21:42
Membernive28073-Mar-13 21:42 
GeneralRe: error while executing Pin
Gaurav Girdher8-Sep-13 20:57
MemberGaurav Girdher8-Sep-13 20:57 
Questionproblem accessing project with credentials Pin
vanita_p6-Feb-13 19:45
Membervanita_p6-Feb-13 19:45 
AnswerRe: problem accessing project with credentials Pin
Gaurav Girdher8-Sep-13 21:04
MemberGaurav Girdher8-Sep-13 21:04 
QuestionDoes this app depend on database load . Pin
rajin kp26-Dec-12 1:10
professionalrajin kp26-Dec-12 1:10 
Questionproblems in implemeting chat Pin
rajin kp25-Dec-12 22:29
professionalrajin kp25-Dec-12 22:29 
GeneralMy vote of 5 Pin
connect.jaswinder15-Apr-12 21:09
Memberconnect.jaswinder15-Apr-12 21:09 
Questionhow to implement this code in c# Pin
Member 875383428-Mar-12 19:17
MemberMember 875383428-Mar-12 19:17 
AnswerRe: how to implement this code in c# Pin
Narsimlu Keshagouni14-May-12 0:45
professionalNarsimlu Keshagouni14-May-12 0:45 
GeneralMy vote of 4 Pin
Marsowl14-Feb-12 16:26
MemberMarsowl14-Feb-12 16:26 
SuggestionWCF implementation to store messages - auther Pin
Narsimlu Keshagouni8-Oct-11 18:59
professionalNarsimlu Keshagouni8-Oct-11 18:59 
QuestionCannot run this. Pin
Member 182069323-Aug-11 23:52
MemberMember 182069323-Aug-11 23:52 
AnswerRe: Cannot run this. Pin
Narsimlu Keshagouni8-Sep-11 22:33
professionalNarsimlu Keshagouni8-Sep-11 22:33 
GeneralCannot run this. Pin
Member 76692031-Oct-11 9:55
MemberMember 76692031-Oct-11 9:55 
GeneralRe: Cannot run this. Pin
Narsimlu Keshagouni6-Oct-11 0:59
professionalNarsimlu Keshagouni6-Oct-11 0:59 
AnswerSteps to configure Pin
Narsimlu Keshagouni20-Feb-11 23:11
professionalNarsimlu Keshagouni20-Feb-11 23:11 
GeneralRe: Steps to configure Pin
dhananjay20179-Aug-12 23:23
Memberdhananjay20179-Aug-12 23:23 
Generalinstallation and execution of this web chat application Pin
salsal1227-Nov-10 19:30
Membersalsal1227-Nov-10 19:30 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.