locked
$.connection is undefined RRS feed

  • Question

  • User81789783 posted

    i have below layout file

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>@ViewBag.Title - Satyaprakash Jquery and SignalR Intro</title>
        <link href="~/Content/bootstrap.css" rel="stylesheet" />
        <script src="~/Scripts/modernizr-2.6.2.js"></script>
        @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
    </head>
    <body>
        <div class="navbar navbar-inverse navbar-fixed-top">
            <div class="container">
                <div class="navbar-header">
    
                    <span class="noti glyphicon glyphicon-globe"><span class="count">&nbsp;</span></span>
                    <div class="noti-content">
                        <div class="noti-top-arrow"></div>
                        <ul id="notiContent"></ul>
                    </div>
                    @Html.ActionLink("Satyaprakash Jquery and SignalR", "Index", "Home", null, new { @class = "navbar-brand" })
                </div>
            </div>
        </div>
        <div class="container body-content">
            @RenderBody()
            <hr />
        </div>
        @* Add Jquery Library *@
    
        <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    
        <script src="~/Content/sweetalert.min.js"></script>
        <script src="/Scripts/ui/jquery.ui.core.js"></script>
        <script src="/Scripts/ui/jquery.ui.widget.js"></script>
        <script src="/Scripts/ui/jquery.ui.mouse.js"></script>
        <script src="/Scripts/ui/jquery.ui.draggable.js"></script>
        <script src="/Scripts/ui/jquery.ui.resizable.js"></script>
        <script src="~/Scripts/jquery.signalR-2.2.0.min.js"></script>
       
        <script src="~/signalr/hubs"></script>
        @*<script src="~/Scripts/jquery-2.2.3.min.js"></script>
        <script src="~/Scripts/jquery.signalR-2.2.0.min.js"></script>
        <script src="/signalr/hubs"></script>
        <script src="~/Scripts/bootstrap.min.js"></script>*@
        @* Add css  *@
        <link href="~/Content/bootstrap.css" rel="stylesheet" />
    
        <style type="text/css">
            /*Added css for design notification area, you can design by your self*/
            /* COPY css content from youtube video description*/
            .noti-content {
                ;
                right: 100px;
                background: yellow;
                color: blue;
                font-size: medium;
                font-style: oblique;
                font-family: Arial;
                border-radius: 4px;
                top: 47px;
                width: 440px;
                display: none;
                border: 1px solid #9E988B;
            }
    
            ul#notiContent {
                max-height: 200px;
                overflow: auto;
                padding: 0px;
                margin: 0px;
                padding-left: 20px;
            }
    
                ul#notiContent li {
                    margin: 3px;
                    padding: 6px;
                    background: #FF6600;
                }
    
            .noti-top-arrow {
                border-color: transparent;
                border-bottom-color: #F5DEB3;
                border-style: dashed dashed solid;
                border-width: 0 8.5px 8.5px;
                ;
                right: 32px;
                top: -8px;
            }
    
            span.noti {
                color: lightgreen;
                margin: 15px;
                ;
                right: 100px;
                font-size: 30px;
                cursor: pointer;
            }
    
            span.count {
                ;
                top: -1px;
                /*color:white;*/
            }
            /*.noti:hover {
                color:white;
            }*/
        </style>
    
        @* Add jquery code for Get Notification & setup signalr *@
        <script type="text/javascript">
                $(function () {
                    // Click on notification icon for show notification
                    $('span.noti').click(function (e) {
                        debugger;
                        e.stopPropagation();
                        $('span.noti').css("color", "lightgreen");
                        $('span.count').hide();
                        $('.noti-content').show();
                        var count = 0;
                        count = parseInt($('span.count').html()) || 0;
                        // only load notification if not already loaded
                        if (count > 0) {
                            updateNotification();
                        }
                        $('span.count', this).html('&nbsp;');
                    })
                    // hide notifications
                    $('html').click(function () {
                        $('.noti-content').hide();
                    })
                    // update notification
                    function updateNotification() {
                        $('#notiContent').empty();
                        $('#notiContent').append($('<li>Loading...</li>'));
                        $.ajax({
                            type: 'GET',
                            url: '/home/GetNotifications',
                            success: function (response) {
                                debugger;
                                $('#notiContent').empty();
                                if (response.length == 0) {
                                    $('#notiContent').append($('<li>Currently You Have No New Notifications.</li>'));
                                }
                                $.each(response, function (index, value) {
                                    $('#notiContent').append($('<li>The User , ' + value.Name+'&nbsp;' +'Of ID' + ' (' + value.ID + ') Is Written Something.</li>'));
                                });
                            },
                            error: function (error) {
                                console.log(error);
                            }
                        })
                    }
                    // update notification count
                    function updateNotificationCount() {
                        $('span.count').show();
                        var count = 0;
                        count = parseInt($('span.count').html()) || 0;
                        count++;
                        $('span.noti').css("color", "white");
                        $('span.count').css({ "background-color": "red", "color": "white" });
                        $('span.count').html(count);
    
                    }
                    // signalr js code for start hub and send receive notification
                    var notificationHub = $.connection.notificationHub;
                    $.connection.hub.start().done(function () {
                        console.log('Notification hub started');
                    });
                    //signalr method for push server message to client
                    notificationHub.client.notify = function (message) {
                        if (message && message.toLowerCase() == "added") {
    
                            updateNotificationCount();
                        }
                    }
                })
        </script>
        @Scripts.Render("~/bundles/jquery")
        @Scripts.Render("~/bundles/bootstrap")
        @RenderSection("scripts", required: false)
    </body>
    </html>

    and below is view

    @{
        ViewBag.Title = "LetsChat";
    
    }
    @{ 
    
    //Layout = null;
    }
    
    
    <link href="~/Content/sweetalert.css" rel="stylesheet" />
    @*<input type="text" placeholder="your session" id="txtSession" />
    <br />
    <input type="button" value="Sign In" id="signIn" />
    <br />
    
    <input type="button" value="Create Session" id="createSession" />
    <br />*@
    
    <div  class="col-lg-10">
        col 9
        </div>
    
        <div id="divContainer" class="col-lg-2">
           
            <div id="div_onlineuser" style="border-style:inset;display:block">
                <div id="header" style="background-color:cornflowerblue">Online Users</div><ul id="notiContent"></ul>
            </div>
    
            <ul id="online"></ul>
            <div id="connlbl" style="display:none" ></div>
            @*<label id="connlbl" style="visibility:hidden" class="control-label"></label><br />*@
            <div id="frndConnId" style="display:none" ></div>
            @*<input type="text"   id="frndConnId" placeholder="Paste your friend's connection Id" />*@
            <label class="control-label">Your Group Message</label><br />
            <div id="divChatWindow" class="chatWindow">
            </div>
            <input class="textbox" type="text" id="txtMessage" />
            <input id="btnSendMsg" type="button" value="Send" class="submitButton" />
            <textarea type="text" class="col-lg-10 text-primary" id="message"></textarea>&nbsp;&nbsp;&nbsp;&nbsp;
    
            <input type="button" class="btn btn-primary" id="sendmessage" value="Send" /><br /><br />
            <img src="~/Content/smile.jpg" width="20" height="20" id="smile" style="cursor:pointer" />
            <img src="~/Content/uff.jpg" width="20" height="20" id="ufff" style="cursor:pointer" />
            <div class="container chatArea">
                <input type="hidden" id="displayname" />
                <div id="discussion"></div>
            </div>
        </div>
        <br />
        <input type="hidden" id="connId" />
        @*<input type="button" value="Sign Out" id="signOut" />*@
        <!--Reference the autogenerated SignalR hub script. -->
        @section scripts {
            @*<script src="~/Scripts/jquery-1.10.2.min.js"></script>
    
            <script src="~/Content/sweetalert.min.js"></script>
            <script src="/Scripts/ui/jquery.ui.core.js"></script>
            <script src="/Scripts/ui/jquery.ui.widget.js"></script>
            <script src="/Scripts/ui/jquery.ui.mouse.js"></script>
            <script src="/Scripts/ui/jquery.ui.draggable.js"></script>
            <script src="/Scripts/ui/jquery.ui.resizable.js"></script>
            <script src="~/Scripts/jquery.signalR-2.2.0.min.js"></script>
            <script src="~/signalr/hubs"></script>*@
            <script>
                var chat;
    
                function getValue(connectionid, username, chat) {
                  
    
                    OpenPrivateChatWindow(connectionid, username, chat);
                }
                function AddMessage(userName, message) {
                 //   alert("AddMessage")
                    $('#divChatWindow').append('<div class="message"><span class="userName">' + userName + '</span>: ' + message + '</div>');
    
                    var height = $('#divChatWindow')[0].scrollHeight;
                    $('#divChatWindow').scrollTop(height);
                }
                function OpenPrivateChatWindow(connectionid, userName, chat) {
                    var ctrId = 'private_' + connectionid;
                   
                    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) {
          
               
                   
                    var div = '<div  id="' + ctrId + '"  style="border: 2px solid black;width:30rem" rel="0">' +
                                '<div class="header">' +
                                    '<div  style="float:right;">' +
                                        '<img id="imgDelete"  style="cursor:pointer;" src="/Images/delete.png"/>' +
                                    '</div>' +
    
                                 '<div style="background-color: lightblue">' + '<span  rel="0">' + userName + '</span>' + '</div>' +
                                    '<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("sdfsd")
                        $textBox = $div.find("#txtPrivateMessage");
                        var msg = $textBox.val();
                       
                        if (msg.length > 0) {
                           
                            sendprivatemessage(userId, userName, $("#connlbl").text(), $('#displayname').val(), msg)
                            $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);
                }
                function AddDivToContainer($div) {
                    $('#divContainer').prepend($div);
                    //$div.draggable({
                    //    handle: ".header",
                    //    stop: function () {
                    //    }
                    // });
                }
    
    
    
                $(function () {
                    // Reference the auto-generated proxy for the hub.
                    chat = $.connection.letsChatHub;
    
                    registerClientMethods(chat);
                    
                    debugger;
    
    
                    // Create a function that the hub can call back to display messages.
                    chat.client.addNewMessageToPage = function (name, message) {
                     
    
    
    
                        $('#discussion').append('<li><strong>' + htmlEncode(name)
                            + '</strong>: ' + htmlEncode(message) + '</li>');
                    };
    
                    chat.client.addNewuserToPage = function (id) {
                    
    
                        var data = id;
    
    
                        $.each(data, function (k, v) {
                            for (var prop in v) {
    
                                var userid = "";
                                var username = "";
                                if (v.hasOwnProperty(prop)) {
                                    alert(prop + ' is ' + v[prop]);
                                    if (prop == "Key")
                                        userid = userid + v[prop]
                                    else
                                        username = username + v[prop]
    
                                }
                                //$('#online').empty();
                                //  $('#online').append('<strong>' + "<a   onclick=getValue(this); href="+ username+">" + userid + "</a>" + "   " + username + "<BR>");
    
                            }
    
                        });
    
    
                    };
    
    
                    // Get the user name and store it to prepend to messages.
                    swal({
                        title: "Lets Chat!",
                        text: "<span style='color:#f8bb86;font-weight:700;'>Enter your name:</span>",
                        type: "input",
                        html: true,
                        showCancelButton: true,
                        closeOnConfirm: true,
                        animation: "slide-from-top",
                        inputPlaceholder: "Your Name"
                    },
                    function (inputValue) {
                        userName = inputValue;
                        if (inputValue === false) return false;
                        if (inputValue === "") {
                            swal.showInputError("You need to type your name!");
                            return false;
                        }
                        $('#displayname').val(inputValue);
    
    
                   
    
                        chat.server.send($('#displayname').val());
    
    
    
    
    
    
                        //ajax call end
                      
    
    
                    });
                    // Set initial focus to message input box.
                    chat.client.showMessage = function () {
                     
                        var retVal;
                        chat.server.getConnections(retVal);
                      
                        // chat.server.GetConnections()
                    }
                    $('#message').focus();
                    $('#message').keypress(function (e) {
                        if (e.which == 13) {//Enter key pressed
                            $('#sendmessage').trigger('click');//Trigger search button click event
                        }
                    });
                    $("#smile").click(function () {
    
                    });
                    function successFunc(data, status) {
                       
                    }
                    function registerEvents(chat) {
                        $("#btnStartChat").click(function () {
                            var name = $("#txtNickName").val();
                            var email = $('#txtEmailId').val();
                            if (name.length > 0 && email.length > 0) {
                                $('#hdEmailID').val(email);
                                chat.server.connect(name, email);
                            }
                            else {
                                alert("Please enter your details");
                            }
                        });
    
                        $("#txtNickName").keypress(function (e) {
                            if (e.which == 13) {
                                $("#btnStartChat").click();
                            }
                        });
    
                        $("#txtMessage").keypress(function (e) {
                            if (e.which == 13) {
                                $('#btnSendMsg').click();
                            }
                        });
    
                        $('#btnSendMsg').click(function () {
                            alert("group")
                            var msg = $("#txtMessage").val();
                         
                            if (msg.length > 0) {
    
                                var userName = $('#displayname').val();
                                chat.server.sendMessageToAll(userName, msg);
                                $("#txtMessage").val('');
                            }
                        });
                    }
    
    
    
    
    
    
    
                    function registerClientMethods(chat) {
                        chat.client.notify = function (message) {
                            alert("notify")
                          
                            if (message && message.toLowerCase() == "added") {
    
                                updateNotificationCount(chat);
                            }
                        }
                       
                        // Calls when user successfully logged in
                        chat.client.onConnected = function (id, userName) {
                         
                            connectionid = id;
                            $("#connlbl").append(connectionid)
                            alert(connectionid)
                            $.ajax({
                                type: "POST",
                                url: "/LetsChat/savetodb?name=" + $('#displayname').val() + "&connid=" + connectionid,
    
                                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 online.</li>'));
                                    }
                                    $.each(response, function (index, value) {
                                    });
                                },
                                error: errorFunc
                            });
                        }
    
                        // On New User Connected
                        chat.client.onNewUserConnected = function (id, name, email) {
                            AddUser(chat, id, name, email);
                        }
    
                        // On User Disconnected
                        chat.client.onUserDisconnected = function (id, userName) {
                            $('#' + id).remove();
    
                            var ctrId = 'private_' + id;
                            $('#' + ctrId).remove();
    
                            var disc = $('<div class="disconnect">"' + userName + '" logged off.</div>');
    
                            $(disc).hide();
                            $('#divusers').prepend(disc);
                            $(disc).fadeIn(200).delay(2000).fadeOut(200);
                        }
    
                        // On User Disconnected Existing
                        chat.client.onUserDisconnectedExisting = function (id, userName) {
                            $('#' + id).remove();
                            var ctrId = 'private_' + id;
                            $('#' + ctrId).remove();
                        }
    
                        chat.client.messageReceived = function (userName, message) {
                           
                            AddMessage(userName, message);
                        }
                        //   Clients.Client(toUserId).sendPrivateMessage(toUserId, fromusername, message, username, toUserId);
                        chat.client.sendPrivateMessage = function (windowId, fromUserName, message, username, fromUserId) {
                            var d = new Date();
                          
                            var ctrId = 'private_' + windowId;
                            //    if (status == 'Click') {
                            if ($('#' + ctrId).length == 0) {
                                // createPrivateChatWindow(chatHub, windowId, ctrId, fromUserName, userEmail, email);
                                // alert("before createPrivateChatWindow")
                                //createPrivateChatWindow(connectionid, ctrId, fromUserName, chat);
                                createPrivateChatWindow(windowId, ctrId, fromUserName, chat);
                                $('#' + ctrId).find('#divMessage').append('<div class="message"><span class="userName">' + fromUserName + '</span>: ' + message + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + '</div>');
                                //chat.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);
                                //    }
                                //});
                            }
                            else {
    
                                $('#' + ctrId).find('#divMessage').append('<div class="message"><span class="userName">' + fromUserName + '</span>: ' + message + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + '</div>');
                                // set scrollbar
                                //   scrollTop(ctrId);
                            }
                            // }
    
                            //if (status == 'Type') {
                            //    if (fromUserId == windowId)
                            //        $('#' + ctrId).find('#msgTypeingName').text('typing...');
                            //}
                            //else { $('#' + ctrId).find('#msgTypeingName').text(''); }
                        }
                    }
    
                    function errorFunc(error) {
                 
                        console.log(error);
                    }
    
                    function updateNotificationCount(chat) {
                       
                        value = $("#connlbl").text();
                      
                        $.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>'  + "<a style=margin-left:-3rem; onclick='getValue(\"" + response[i].ContextID + "\",\"" + response[i].Name + "\",\"" + chat + "\");' href='#'>" + response[i].Name + "</a><br />");
    
    
                                }
                                $.each(response, function (index, value) {
    
    
                                });
                            },
                            error: errorFunc
                        });
                    }
    
    
                    // Start the connection.
                    $.connection.hub.start().done(function () {
                        alert("start done")
    
                        registerEvents(chat)
    
    
                        $('#sendmessage').click(function () {
                           
                            var connId = $("#connId").val();
                           
                            var frndConnId = $("#frndConnId").val();
                           
                            //  var finalConnId = frndConnId == "" ? $.connection.hub.id : frndConnId; work fine in case when there is no freind id selected (can enable these line i.e for run time generation friend id)
                            var finalConnId = frndConnId
                          
                            chat.server.send($('#displayname').val(), $('#message').val(), finalConnId);
    
                            
                            $("#connId").val($.connection.hub.id);
                            if (frndConnId == "") {
                                swal("You connection Id", $.connection.hub.id, "success");
                            }
    
                            /*******************create another textbox for separate*******************************************/
    
    
                            /*******************create another textbox for separate*******************************************/
    
                            // Clear text box and reset focus for next comment.
                            $('#discussion').append('<li><strong>' + htmlEncode($('#displayname').val())
                           + '</strong>: ' + htmlEncode($('#message').val()) + '</li>');
                            $('#message').val('').focus();
                        });
                    });
    
    
    
    
    
                  
                })
    
                function sendprivatemessage(userid, connid, fromuerid, fromusername, msg) {
                    alert()
                    chat.server.sendPrivateMessage(userid, connid, fromuerid, fromusername, msg);
    
                    // $('#privatemessagelogs').append('<li><strong>You sent: </strong>:&nbsp;&nbsp;' + $("#txtPrivateMessage").val() + '</li>');
                }
                // This optional function html-encodes messages for display in the page.
                function htmlEncode(value) {
    
                    var encodedValue = $('<div />').text(value).html();
                    return encodedValue;
                }
            </script>
        }
    

    its giving below error ,any help

    TypeError: $.connection is undefine

    Saturday, June 8, 2019 5:55 AM

Answers

  • User81789783 posted

    i have solved my self . chrome is more precise to show error,there was certain hub connection class variable

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, June 8, 2019 3:14 PM

All replies

  • User475983607 posted

    The error very clear.  You are trying to use $.connection before it has been initialized.  Click the error in the console to show the exact line of code that caused the issue.  That should help you find the bug in your code.  

    Saturday, June 8, 2019 1:15 PM
  • User81789783 posted

    i have solved my self . chrome is more precise to show error,there was certain hub connection class variable

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, June 8, 2019 3:14 PM