locked
unable to find chat hub server in user define function RRS feed

  • Question

  • User81789783 posted

    i have below calling chain of function in chat application

     function registerClientMethods(chat) {
                    chat.client.notify = function (message) {
                        alert("notify")
                        alert(chat)
                        if (message && message.toLowerCase() == "added") {
    
                            updateNotificationCount(chat);
                        }
                    }
    }

    where alert (chat) shows [object object]

         function updateNotificationCount(chat) {
               
                    value = $("#connlbl").text();
                   // alert("value: " + value)
                    $.ajax({
                        type: "POST",
                        url: "/LetsChat/GetOnlineusers?connid=" + value,
                  
                        contentType: "application/json; charset=utf-8",
                   
                        dataType: "json",
                        success: function (response) {
                            debugger;
                            $('#notiContent').empty();
                           
                            if (response.length == 0) {
                                $('#notiContent').append($('<li>Currently You Have No New users.</li>'));
                            }
    
                            for (var i = 0, len = response.length; i < len; i++) {
                 
                              
                                $('#notiContent').append('<strong>' + (i + 1) + "<a onclick='getValue(\"" + response[i].ContextID + "\",\"" + response[i].Name + "\",\""+ chat +"\");' href='#'>" + response[i].Name + "</a><br />");
                             
    
                            }
                            $.each(response, function (index, value) {
                              
                              
                            });
                        },
                        error: errorFunc
                    });
                }
     function getValue(connectionid,username,chat) {
            alert (chat)
                alert("connectionid is " + connectionid);
                alert("user name " + username)
           
             //   $("#frndConnId").val(a)
    
                OpenPrivateChatWindow(connectionid, username, chat);
            }
       function OpenPrivateChatWindow(connectionid, userName, chat) {
                var ctrId = 'private_' + connectionid;
                alert("ctrId "  +ctrId)
                alert($('#' + ctrId).length)
                if ($('#' + ctrId).length > 0) return;
    
                createPrivateChatWindow(connectionid, ctrId, userName,chat);
    
                //chatHub.server.getPrivateMessage(userEmail, email, loadMesgCount).done(function (msg) {
                //    for (i = 0; i < msg.length; i++) {
                //        $('#' + ctrId).find('#divMessage').append('<div class="message"><span class="userName">' + msg[i].userName + '</span>: ' + msg[i].message + '</div>');
                //        // set scrollbar
                //        scrollTop(ctrId);
                //    }
                //});
            }
            function createPrivateChatWindow(userId, ctrId, userName,chat) {
                alert("createPrivateChatWindow method")
    
                var div = '<div id="' + ctrId + '" class="ui-widget-content draggable" rel="0">' +
                            '<div class="header">' +
                                '<div  style="float:right;">' +
                                    '<img id="imgDelete"  style="cursor:pointer;" src="/Images/delete.png"/>' +
                                '</div>' +
    
                                '<span class="selText" rel="0">' + userName + '</span>' +
                                '<span class="selText" id="msgTypeingName" rel="0"></span>' +
                            '</div>' +
                            '<div id="divMessage" class="messageArea">' +
    
                            '</div>' +
                            '<div class="buttonBar">' +
                                '<input id="txtPrivateMessage" class="msgText" type="text"   />' +
                                '<input id="btnSendMessage" class="submitButton button" type="button" value="Send"   />' +
                            '</div>' +
                            '<div id="scrollLength"></div>' +
                        '</div>';
    
                var $div = $(div);
    
                // ------------------------------------------------------------------ Scroll Load Data ----------------------------------------------------------------------//
    
                //var scrollLength = 2;
                //$div.find('.messageArea').scroll(function () {
                //    if ($(this).scrollTop() == 0) {
                //        if ($('#' + ctrId).find('#scrollLength').val() != '') {
                //            var c = parseInt($('#' + ctrId).find('#scrollLength').val(), 10);
                //            scrollLength = c + 1;
                //        }
                //        $('#' + ctrId).find('#scrollLength').val(scrollLength);
                //        var count = $('#' + ctrId).find('#scrollLength').val();
    
                //        //chatHub.server.getScrollingChatData(userEmail, email, loadMesgCount, count).done(function (msg) {
                //        //    for (i = 0; i < msg.length; i++) {
                //        //        var firstMsg = $('#' + ctrId).find('#divMessage').find('.message:first');
    
                //        //        // Where the page is currently:
                //        //        var curOffset = firstMsg.offset().top - $('#' + ctrId).find('#divMessage').scrollTop();
    
                //        //        // Prepend
                //        //        $('#' + ctrId).find('#divMessage').prepend('<div class="message"><span class="userName">' + msg[i].userName + '</span>: ' + msg[i].message + '</div>');
    
                //        //        // Offset to previous first message minus original offset/scroll
                //        //        $('#' + ctrId).find('#divMessage').scrollTop(firstMsg.offset().top - curOffset);
                //        //    }
                //        //});
                //    }
                //});
    
                //// DELETE BUTTON IMAGE
                //$div.find('#imgDelete').click(function () {
                //    $('#' + ctrId).remove();
                //});
    
                // Send Button event
                $div.find("#btnSendMessage").click(function () {
                    alert("send click")
    
                    $textBox = $div.find("#txtPrivateMessage");
                    var msg = $textBox.val();
                    alert("msg is  " + msg)
                    if (msg.length > 0) {
                        chat.server.sendPrivateMessage(userId, $("#connlbl").text(), msg, 'Click');
                        $textBox.val('');
                    }
                });
    
                // Text Box event
                $div.find("#txtPrivateMessage").keyup(function (e) {
                    if (e.which == 13) {
                        $div.find("#btnSendMessage").click();
                    }
    
                    // Typing
                    $textBox = $div.find("#txtPrivateMessage");
                    var msg = $textBox.val();
                    if (msg.length > 0) {
                        chat.server.sendPrivateMessage(userId, msg, 'Type');
                    }
                    else {
                        chat.server.sendPrivateMessage(userId, msg, 'Empty');
                    }
    
                    clearInterval(refreshId);
                    checkTyping(chat, userId, msg, $div, 5000);
                });
    
                AddDivToContainer($div);
            }

    here is an error

    TypeError: chat.server is undefined

    LetsChat:193:21
        createPrivateChatWindow http://localhost:55590/LetsChat/LetsChat#:193
        jQuery 2

    TypeError: chat.server is undefinedLetsChat:178:21

        createPrivateChatWindow http://localhost:55590/LetsChat/LetsChat#:178
        jQuery 2

    any help ,I mean chat object is not identified

    Sunday, June 2, 2019 2:03 PM

Answers

  • User61956409 posted

    Hi erum,

    You posted many threads discussed similar issue, I suggest that you can create and use a global proxy object to communicate with your hub instead of passing proxy object between functions.

    Besides, if you'd like to implement sending private message functionality in your application by clicking a specific user from online user list, please refer to the following sample code.

    <!DOCTYPE html>
    <html>
    <head>
        <title>SignalR Simple Chat</title>
        <style type="text/css">
            .container {
                background-color: #99CCFF;
                border: thick solid #808080;
                padding: 20px;
                margin: 20px;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <input type="text" id="message" />
            <input type="button" id="sendmessage" value="Send" />
            <input type="hidden" id="displayname" />
            <ul id="discussion"></ul>
        </div>
        <input type="hidden" id="connId" value="" />
        <h2>Online Users</h2>
        <div class="container">
            <!--<ul id="user_list"></ul>-->
            <div id="online"></div>
        </div>
        <br />
        <br />
        <div>
            <h2>Private Message</h2>
            <div id="user_id"></div>
            <input type="text" id="txtPrivateMessage" />
            <input type="button" id="sendprivatemessage" value="Send Private Message" onclick="sendprivatemessage()" />
            <input type="hidden" id="pconnId" value="" />
            <ul id="privatemessagelogs"></ul>
        </div>
        <!--Script references. -->
        <!--Reference the jQuery library. -->
        <script src="Scripts/jquery-1.6.4.min.js"></script>
        <!--Reference the SignalR library. -->
        <script src="/Scripts/jquery.signalR-2.0.0.js"></script>
        <!--Reference the autogenerated SignalR hub script. -->
        <script src="/signalr/hubs"></script>
        <!--Add script to update the page and send messages.-->
        <script type="text/javascript">
            var chat;
            $(function () {
                chat = $.connection.chatHub;
    
                chat.client.broadcastMessage = function (name, message) {
                    var encodedName = $('<div />').text(name).html();
                    var encodedMsg = $('<div />').text(message).html();
                    $('#discussion').append('<li><strong>' + encodedName
                        + '</strong>:&nbsp;&nbsp;' + encodedMsg + '</li>');
                };
    
                //update online users
                chat.client.addNewuserToPage = function (ids) {
                    $('#online').empty();
                    var conid = $("#connId").val();
                    $.each(ids, function (k, v) {
                        console.log(v["Key"] + "/" + v["Value"]);
    
                        if (v["Key"].toString() != conid.toString()) {
                            $('#online').append('<strong>' + "<span onclick=getValue('" + v["Key"] + "','" + v["Value"] + "')>" + v["Key"] + "</span>" + "   " + v["Value"] + "<BR>");
                        }
                    });
                }
    
    
                var username = prompt('Enter your name:', '');
                $('#displayname').val(username);
    
    
                $('#message').focus();
                //$.connection.hub.logging = true;
                $.connection.hub.start().done(function () {
                    var conid = $.connection.hub.id;
                    $("#connId").val(conid);
                    chat.server.send($('#displayname').val(), conid);
    
                    $('#sendmessage').click(function () {
                        //chat.server.send($('#displayname').val(), $('#message').val());
                        chat.server.send($('#displayname').val(), $('#message').val(), conid);
                        $('#message').val('').focus();
                    });
                });
            });
    
            function getValue(userId, name) {
                $("#user_id").text("Name: " + name + "Connection Id: " + userId);
    
                $("#pconnId").val(userId);
    
                $("#txtPrivateMessage").val("");
    
                $('#privatemessagelogs').empty();
                //alert("ccc:" + userId);
            }
    
            function sendprivatemessage() {
                chat.server.sendPrivateMessage($('#displayname').val(), $("#pconnId").val(), $("#txtPrivateMessage").val());
    
                $('#privatemessagelogs').append('<li><strong>You sent: </strong>:&nbsp;&nbsp;' + $("#txtPrivateMessage").val() + '</li>');
            }
        </script>
    </body>
    </html>

    Hub Class

    public static List<KeyValuePair<string, string>> ConnectedIds = new List<KeyValuePair<string, string>>();
    
    private string name = "";
    
    
    public void Send(string name, string message, string connId)
    {
        Clients.AllExcept(connId).broadcastMessage(name, message);
        //Clients.Client(connId).addNewMessageToPage(name, message);
    }
    
    public void Send(string name, string connId)
    {
        ConnectedIds.Add(new KeyValuePair<string, string>(connId, name));
    
        Clients.All.addNewuserToPage(ConnectedIds);
                
    }
    
    public void sendPrivateMessage(string name, string connId, string message)
    {
        Clients.Client(connId).broadcastMessage(name, message + " (private message)");
    }

    Test Result:

    With Regards,

    Fei Han

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, June 3, 2019 7:19 AM