SignalR fails to trigger client callback function

Currently, I am diving into the world of SignalR and attempting to create a basic message notification system. However, despite my limited understanding of SignalR, I am unable to display the messages after submission.

I have researched multiple blogs on this topic and it seems that the key is to have a VOID method that takes a string value and then sends it back by attaching it to the Clients context. However, I am encountering issues as the onReceiveNotification() function is always undefined in the JS debugger.

Am I overlooking something?

notificationhub.cs

[HubName("notificationHub")]
public class NotificationHub : Hub
{

    public override System.Threading.Tasks.Task OnConnected()
    {
        return base.OnConnected();
    }

    public override System.Threading.Tasks.Task OnDisconnected(bool stopCalled)
    {
        return base.OnDisconnected(stopCalled);
    }

    public override System.Threading.Tasks.Task OnReconnected()
    {
        return base.OnReconnected();
    }

    [HubMethodName("sendNotifications")]
    public void SendNotifications(string message)
    {
        Clients.All.onRecieveNotification(string.Format("{0} {1}", message, DateTime.Now.ToString()));
    }
}

message.html page

<div>
    <input type="text" id="messageinput" />
    <button id="notifybutton">Send Message</button>
</div>

<script src="Scripts/jquery-2.1.4.min.js"></script>
<script src="Scripts/jquery.signalR-2.2.0.min.js"></script>
<script src="signalr/hubs"></script>
<script type="text/javascript">
    jQuery(document).ready(function ($)
    {
        var $hub = $.connection.notificationHub;
        $.connection.hub.start();

        $(document).on("click", "#notifybutton", {}, function (e)
        {
            e.preventDefault();
            var $message = $("#messageinput").val();
            $hub.server.sendNotifications($message);
        });
    });
</script>

display.html

<div>
    <ul id="messages"></ul>
</div>

<script src="Scripts/jquery-2.1.4.min.js"></script>
<script src="Scripts/jquery.signalR-2.2.0.min.js"></script>
<script src="signalr/hubs"></script>
<script type="text/javascript">
    jQuery(document).ready(function ($)
    {
        var $hub = $.connection.notificationHub;

        $hub.onRecieveNotification = function (message)
        {
            $("#message").append($("<li></li>", { text: message }));
        }

        $.connection.hub.start();
    });
</script>

Answer №1

Seems like there's a missing element called client in the following code snippet:

   $hub.client.onRecieveNotification = function (message)
    {
        $("#message").append($("<li></li>", { text: message }));
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Personalize JSON Reporter to Display Captured Information - WebdriverIO

I'm currently in the process of scraping data from an android app using WDIO and APPIUM. After successfully storing the scraped data in an array, I now aim to automatically output this array data to a .json file, rather than manually copying and pasti ...

Instructions for attaching an event listener to a Threejs Mesh Object with the help of threex dom events

var domEvents = new THREEx.DomEvents(camera, view.domElement); var div = document.createElement( 'div' ); div.setAttribute('data-remove','mesh1'); div.className = 'close-me'; var label = new THREE.CSS2DObje ...

Issue with SeeTest: Element remains unclicked

Recently I began exploring mobile automation through SeeTest and decided to automate a Gmail account on a mobile browser. During the recording, I was able to capture the "Switch account" element. However, when it came time to execute the automation, the ...

Check an array of objects for duplicate key-value pairs by cross-referencing other key-value pairs within the array using JavaScript

let selectedFruit = "mango" let fruitArray = [{fruit:"apple",locale:"US"}, {fruit:"orange",locale:"US"}, {fruit:"banana",locale:"US"}, {fruit:"apple",locale:"US"}, {fruit:"orange",locale:"IT"}, {fruit:"apple",locale: ...

Changing Images with Jquery on Click Event

This section of the HTML document contains an image link that is designed to switch between two images when clicked. The images in question are timeline-hand and hand-clicked. Clicking on the image should change it from one to the other and vice versa. Ho ...

Exploring the Dynamic Routing Features of Next.js

After diving into Next.js, I found the learning curve to be manageable since React was already familiar territory for me. Currently, my focus is on implementing dynamic routing in my application - Starting with my live/index.js file - (Where I utilize ge ...

Incorporating object data and a value into an Angular $http.post request and retrieving them in an ASP .NET Web API

I am seeking a way to send multiple objects and a value from an Angular application to an ASP .NET Web API. Below is the snippet of my JavaScript code: var productStockArray = $scope.ProductStockArray; var challan = 20; $http.post(dataUrl + "StockProduc ...

Adding information to Google Cloud Firestore while disconnected from the internet

I am currently facing an issue with my code. It works perfectly fine when the application is online, but fails to execute the promise resolution or rejection when offline. I have searched through the cloud firestore documentation and found examples on qu ...

Setting up vue-apollo 3.0.0 Beta

Seeking guidance as a newcomer in this field. I have experience with Authentication using Apollo client, but I'm stuck when trying to integrate the new vue-apollo-plugin into my Vue-cli-3 generated project. Specifically, I'm confused about how an ...

Is there a way to change my cursor to a pointer finger when hovering over my box?

<script type="text/javascript"> function draw() { var canvas = document.getElementById('Background'); if (canvas.getContext) { var ctx = canvas.getContext('2d'); ctx.lineWidth = 0.4 ctx.strokeRect(15, 135, 240, 40) Is there a w ...

Tips on dividing and recycling mongodb connection in Node.js

I am currently troubleshooting the connection to MongoDB using Node.js. The code I have in a file named mongodb.js is as follows: const mongoClient = require('mongodb').MongoClient; const env = process.env.NODE_ENV || 'development'; co ...

Managing the onChange event for a MaterialUI dropdown component

I'm encountering an issue with validating the MaterialUI TextField component (Country list) wrapped with Autocomplete. I am trying to use the onChange event to enable the Submit button when the country field is filled in. However, the problem arises w ...

Struggling to access properties of a javascript object while trying to slice it within table pagination

As I work on this program, my goal is to apply a function to an Array of objects to display rows with information from this group of users. However, TypeScript is throwing various errors when I try to access this information. I'm unsure of what I&apos ...

Streamline event listeners with a pair of attributes

I am working with a function that requires one parameter: function magical(element){ ... } In my project, I have multiple click handlers attached to different elements and classes that are invoking this function: $('#div1').click(function(){ ...

How to access the ID value from the URL within a different component that was passed as a prop in

I have a scenario where I am building a reusable component with two child components in the following flow: Child Component 1 -> Parent Component -> Super Parent Main Component In the child component, I define a prop called 'url' which is ...

Tips for streamlining distinct states and generalized state in UI Router

I've set up the following configuration in my JS app under the $stateProvider section using angular ui-router: .state('login', { url: '/login', templateUrl: 'app/login/login.tmpl.html', controller: &apo ...

Converting UWP Json to C# code

After receiving some JSON data from the web, I needed to serialize it into classes and utilize the information. To achieve this, I visited a helpful website that converts JSON to C# classes. json: [{"line_descr":"\u03a0\u0395\u0399\u03 ...

Utilizing global variables in Vue.js while working with the CLI template

How can I create a global variable in my Vue.js app that is accessible by all components and modifiable by any of them? I am currently utilizing the CLI template. Any recommendations on how to achieve this? Appreciate your assistance. Dhiaa Eddin Anabtaw ...

Utilizing Cookies within an HTTPModule

Having trouble with setting cookies in a custom http module. Trying to set the cookie during the BeginRequest event like this: HttpCookie myCookie = new HttpCookie(config.CookieName); SitePrefCookie["key1"] = value1; SitePrefCookie["key2"] = value2; Si ...

Discover the most concise string within the array

Is there a way to determine the shortest string in a JavaScript array regardless of the number of elements it contains? I attempted using var min = Math.min(arr[0].length,arr[1].length,arr[2].length); to find the shortest string among 3 elements in an ar ...