``There seems to be an issue with receiving updates from the API in Signal R

After following a tutorial on the Microsoft site for creating a SignalR app, I attempted to use a local API to update a counter in real-time using AJAX.

function getALL() {
  $.ajax({
    url: 'http://localhost:8080/api/GetCount',
    contentType: 'application/json ; charset:utf-8',
    type: 'GET',
    success: function (data) {
        console.log(data);
        document.getElementById("messageList").innerHTML = data[0].Count;
    }
  });
}

I then initialized the hub with:

var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();

connection.on("ReceiveMessage", function () {
  getALL();
});

connection.start().then(function () {
  getALL(); 
  connection.invoke("SendMessage").catch(function (err) {
    return console.error(err.toString());
});
}).catch(function (err) {
  return console.error(err.toString()); 
});

Although this code initially worked and displayed the data, it did not update when a new row was added. I wondered if my implementation of AJAX was incorrect or if my hub needed an Entity Model.

Below is a snippet from my Hub:

    public class ChatHub : Hub
    {
        private IHubContext<ChatHub> _hubContext;

        public ChatHub(IHubContext<ChatHub> hubContext) { _hubContext = hubContext; }

        public async Task SendMessage()
        {
            await _hubContext.Clients.All.SendAsync("ReceiveMessage");
        }
    }
}

I also included the hub in my Startup.cs file as recommended:

app.UseEndpoints(endpoints =>
        {
            endpoints.MapHub<ChatHub>("/chatHub");
            endpoints.MapFallbackToPage("/_Host");
        });

I am working with net Core 3.1 and any guidance would be appreciated. This seemingly simple modification has been challenging thus far. Thank you for your help.

Answer №1

In order to receive notifications from the hub when a change occurs, you will need to implement the following code:

connection.invoke("SendMessage").catch(function (err) {
    return console.error(err.toString());
});

This code should not be executed immediately after starting the connection, but rather after every addition of a new row in your application. Edit: Here is an example of what needs to be done: 1. Implement an event in your signalR client that triggers when a row is added and execute the code mentioned above. 2. Ensure that another (or the same) signalR client is notified as needed. Simply adding a row directly does not update the database. You must add the row in the frontend and inform the hub through your client-side application.

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

Interactive Thumbnail Previews

There seems to be an issue with the thumbnail links on my page. The leftmost and rightmost links work fine, but the middle ones are not functioning properly when clicked. The PHP code used to generate these links is the same for all of them, so it's p ...

How to use expressjs to fetch an image from a URL and show it on a webpage

I am currently running an image API from my home server, and I am working on creating a cloud-hosted page that will retrieve the image in the backend and display it, adding a layer of abstraction. My goal is to achieve the following: index.js var express ...

Can you explain the variance between Angular 1.4.3's $http long form and shorthand methods?

Trying to decide between using the $http service in Angular the traditional way or the shortcut method – which one is better? Is there any impact on development, performance, or is it just a matter of personal preference? Personally, I lean towards the ...

The loading time of Javascript is dragging on

The loading sequence for the javascript in the "intro" div is currently causing a delay. The background image loads first, followed by the javascript, resulting in a slow overall load time. Is there a way to display a "loading please wait" message within t ...

The values in each row of the table are dynamically updated according to the option selected in the dropdown

I am working on a project to create a dynamic page with a form that includes Total and Converted Total Value fields. The total value is generated through a PHP do-while loop. The page also features a currency dropdown at the top. When a currency is selecte ...

Is there a way to switch between modals with the same ID using JavaScript?

I currently have a modal window open which contains a paginated list. Within this modal, I have next/previous buttons that are supposed to display new content. Since this functionality needs to work on multiple pages, I can't include HTML code for th ...

I am puzzled as to why this particular contact form is not functioning properly

I'm having trouble figuring out why my form isn't functioning properly. I receive a success message, but nothing is being delivered to my inbox. I even checked my spam folder to no avail. After waiting patiently for a few minutes, still no sign o ...

Variable for Ajax success not set even though the other data was returned

UPDATE: While the main question remains unchanged, I have modified the approach to now return a getButtons() function instead of a global buttons array. I am utilizing an AJAX request to fetch data from the server in order to populate a popup box, which i ...

Discover the power of xpath in locating parent elements using c# and selenium!

On the website where I am testing, there are two modal dialogs that have almost identical designs. They are used to either enable or disable a parameter on the webpage. In fact, the code for both modals is essentially the same. I need to access the button ...

Increase the number of file upload fields available for use

I've implemented this code to enable users to create additional upload fields. The fields are created successfully, and users can select a file. However, the selected file is not added to the input field except for the first one. On inspecting with fi ...

Does the Node Schedule library create new processes by spawning or forking them?

Is the node-schedule npm module responsible for spawning/forking a new process, or do we need to handle it ourselves? var cron = require('node-schedule'); var cronExpress="0 * * * *"; cron.scheduleJob(cronExpress, () => { //logger.info(" ...

Tips for correctly updating the status of a checkbox linked to a database

I need some guidance on handling the state change of an input checkbox in React. The checkbox's initial value is determined by a boolean retrieved from a database. Currently, I am using defaultChecked to set the checkbox initially based on this boolea ...

Encountering a problem converting a MongoDB document to a POCO

Here is the structure of my document: { "_id" : ObjectId("58064346e74f22124037a607"), "Date" : ISODate("2016-10-18T15:44:01.083Z") } And this is how my POCO looks like: public class MyClass { public ObjectId _id; Public BsonDateTime Date; ...

Extracting and passing a JSON object to a Spring controller

I have a file upload feature on my jsp page that specifically accepts json format files. I want to retrieve the uploaded json file and pass it to a Spring controller for further processing. This is how my javascript code appears: var file = this.files[0] ...

Tips for saving a document in a table without using the _id field

I want to save the employee object without the _id attribute, just the "employee" attribute as shown below: "employee" :[ { "name" : "leila", "idemployee" : ObjectId("59319505efa50b137477a1f4"), ...

PHP AJAX autocomplete - achieving precise matches

As I work on my PHP/MySQL/Ajax Autocomplete app, I am delighted by its ability to display available addresses in real-time while the user types, much like Google Maps. The application functions smoothly and displays results accurately: https://i.sstatic.n ...

How can Windows technologies be used to detect copy, paste, and print system commands?

Are there methods available to identify copy, paste, and print actions using Windows technologies? For instance, if an Excel application is open and a user attempts to print or copy the sheet, is it possible to detect these events? If so, could someone p ...

Memory loss issue due to nested objects in .NET 4 LinkedList

Edit: Disregard this inquiry, as it is related to a specific programmer error known as "PBCAK". Section 1 In what way can the memory leak present in this code be rectified? Section 2 If resolving the issue involves adding Dispose to SummaryEntity, how ...

PHP for loop malfunctioning when working with JSON encoding

I'm having trouble retrieving member ratings from the database using ajax. I included a function in the JSON, and while it returned a value within the function, it didn't execute the for loop as expected. Below is my code where the loop failed t ...

Tips for transferring data using the GET method from the client side to the server side via AJAX

I am attempting to send two dates - a start date and an end date, in order to retrieve data between those two dates. However, my current implementation is not working as expected. $(document).ready(function(){ const date_inputs = new FormData(); ...