'Multiple signalR connections on the same hub from a single user
I have used SignalR in my ASP.NET Core MVC project. The connection string in user page is:
var connection = new signalR.HubConnectionBuilder().withUrl("/signalRServer").withAutomaticReconnect().build();
connection.start().then( result => {
console.log("Connection has been established suucessfully.")
I use this connection string to get instant notifications and it works well. Recently, I tried to add an another functionality to the user page. I want to send signal to admin page, when a file is uploaded by user. This signal is sent to the hub when the following function is called:
<script>
function sendNotification(pmId, pmNumber){
var notificationText = "PM" + pmNumber + "uploaded";
var formData = new FormData();
formData.append("notificationText", notificationText);
$.ajax({
type: "POST",
url: "/Page/SendUploadNotification",
processData: false,
contentType: false,
data: formData,
success: function(response){
if(response.success){
var notificationId = response.notificationId;
connection.invoke("FileUploadNotification", notificationId, notificationText).catch(function(err){
return console.error(err)
});
location.reload();
}else{
alert("Error!");
}
}
});
}
</script>
The problem is that when the function above is called, it cannot use the signalR connection that has been defined earlier. Console says:
Uncaught ReferenceError: connection is not defined at Object.success (pmPage:655:21) at c (jquery-3.6.0.min.js:2:28327) at Object.fireWith [as resolveWith] (jquery-3.6.0.min.js:2:29072) at l (jquery-3.6.0.min.js:2:79901) at XMLHttpRequest. (jquery-3.6.0.min.js:2:82355)
How can I fix this problem?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
