Callback on client does not get triggered with SignalR - javascript

I'm currently getting up to speed with SignalR, and tried to build a very basic message notification system using the very basic understanding of SignalR that I have but I can't get the messages to come back after the submission.
I've read up on numerous blogs on the topic and the very basic is to have a VOID method that accepts a string value and then passes that back by attaching it to the Clients context, however, this does not work for, as onReceiveNotification() is always undefined in JS debugger?
Am I missing 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>

It looks like you are missing client in:
$hub.client.onRecieveNotification = function (message)
{
$("#message").append($("<li></li>", { text: message }));
}

Related

JavaScript connection not starting and function not executing on a JQuery and SignalR web form application

I have a ASP.NET chat application. Using JavaScript, Jquery and Signalr. However my connection does not start to post the message. The browser does prompt me to enter my alias however when l write my message. It does not post it. This is a snippet of the error
C# class :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
namespace Synergince
{
[HubName("chatHub")]
public class ChatHub : Hub
{
public void Send(string name, string message)
{
Clients.All.broadcastMessage(name, message);
}
}
}
JavaScript code :
<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>
//Script references
<script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>
<script type="text/javascript" src="Scripts/jquery.signalR-1.2.1.js">
</script>
<script src='<%: ResolveClientUrl("~/signalr/hubs") %>'></script>
<script type="text/javascript">
$(document).ready(function () {
//declare a proxy to reference the hub
var chat = $.connection.chatHub;
//function for the hub to call to broadcast messages
chat.client.broadcastMessage = function (name, message) {
$('#discussion').append('<li><strong>' + name + '</strong>: ' + message + '</li>');
};
//Get the user name and store it to prepend to messages
$('#displayname').val(prompt('Enter preferred alias:', ''));
//initial focus on textbox
$('#message').focus();
//connection start
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
var Name = $('<div />').text($('#displayname').val()).html();
var Msg = $('<div />').text($('#message').val()).html();
//call send method to hub
chat.server.send(Name, Msg);
//clear textbox and set for next input
$('#message').val('').focus();
});
});
});
</script>
</form>
Browser debugger error is:
Uncaught TypeError: $.Deferred is not a function
To this line :
$.connection.hub.start().done(function () {
Not sure what you are trying to achieve with the two VARs below.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
var Name = $('<div />').text($('#displayname').val()).html();
var Msg = $('<div />').text($('#message').val()).html();
//call send method to hub
chat.server.send(Name, Msg);
//clear textbox and set for next input
$('#message').val('').focus();
});
I can only assume you want to send the value of the input boxes. Essentially the same as the sample Chat on the SignalR site.
Change your function to get the "val" of the input:
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});

Cant submit html form after use js script

I have this html site
<html>
<head>
<link rel="stylesheet" href="~/Content/index.css" />
<link rel="stylesheet" href="~/Scripts/fancyBox/source/jquery.fancybox.css" type="text/css" media="screen" />
<meta name="viewport" content="width=device-width" />
<script type="text/javascript" src="~/Scripts/prototype.js"></script>
<script type="text/javascript" src="~/Scripts/scriptaculous.js?load=effects"></script>
<script type="text/javascript" src="~/Scripts/Scale.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="~/Scripts/fancyBox/source/jquery.fancybox.pack.js"></script>
<title>Countries</title>
</head>
<body>
<div>
#foreach (var country in Model)
{
<a class="fancybox">
<div class="tooltip">
#using (Html.BeginForm("ChangeCulture", "Home", new { lang = country.Culture }))
{
<!-- onclick="zoomIn('#country.Culture')"-->
<input id="#country.Culture" class="#country.Sprite" type="image" name="submit" src="//" />
<span class="tooltiptext">#country.Country</span>
}
</div>
</a>
}
</div>
<script type="text/javascript">
$(document).ready(function () {
$(".fancybox").fancybox({
afterShow : function() {
this.find("form").submit();
}
});
})
</script>
</body>
</html>
The bottom line is that the flags of countries with tooltips are displayed on the screen and by pressing it is necessary to change the language of the tooltips to the language used in the country. I did this, and now I need to increase the whole screen after receiving the picture with the flag, and then the language would change. I found the fancybox scripts, but after it is inserted, the form is not sent, the selected flag appears in the center, but nothing happens after that, what could be the problem? I have not written to asp and js before
After click on the image I got an error
Uncaught TypeError: this.find is not a function
at Object.afterShow (Index:119)
at Function.trigger (jquery.fancybox.pack.js:17)
at HTMLDivElement._afterZoomIn (jquery.fancybox.pack.js:33)
at HTMLDivElement.d.complete (jquery-latest.min.js:4)
at j (jquery-latest.min.js:2)
at Object.fireWith [as resolveWith] (jquery-latest.min.js:2)
at i (jquery-latest.min.js:4)
at m.fx.tick (jquery-latest.min.js:4)
My method
public ActionResult ChangeCulture(string lang)
{
var returnUrl = this.Request.UrlReferrer?.AbsolutePath;
var cookie = this.Request.Cookies["lang"];
if (cookie != null)
{
cookie.Value = lang;
}
else
{
cookie = new HttpCookie("lang")
{
HttpOnly = false,
Value = lang,
Expires = DateTime.Now.AddYears(1)
};
}
this.Response.Cookies.Add(cookie);
return this.Redirect(returnUrl ?? "Index");
}
You should user jquery selector
<script type="text/javascript">
$(document).ready(function () {
$(".fancybox").fancybox({
afterShow : function() {
$(".fancybox").submit();
}
});
})
The error is located in this statement:
this.find("form").submit();
You're trying to call find() method on plain JS object inside this wrapper, where the function belongs to a jQuery object. The correct way is using jQuery object like this:
<script type="text/javascript">
$(document).ready(function () {
$(".fancybox").fancybox({
afterShow : function() {
// alternative: use $(this).closest("form").submit();
$(this).find("form").submit();
}
});
});
</script>
Additionally your redirection method in controller action should be like below, since Controller.Redirect requires full path or URL for redirect to another page:
public ActionResult ChangeCulture(string lang)
{
var returnUrl = this.Request.UrlReferrer?.AbsolutePath;
// cookie settings here
if (string.IsNullOrEmpty(returnUrl))
{
return this.RedirectToAction("Index");
}
return this.Redirect(returnUrl);
}
The this in this.find("form") is not $(".fancybox") here.
Try using $('.fancybox form') instead.

Cannot read property 'counterHub' of undefined

I am trying to make a simple user counter with SignalR, but for unknown reasons to me I am getting this error in the console. I am very new to signalR and asp.net, but what I have make sense to me, and I don't know why am I getting the error. Can somebody please help me solve this and possibly explain why it is happening?
Here is the code in the Index view.
<div class="row">
Number of online users <strong id="counter"></strong>
<script src="#Url.Content("~/Scripts/jquery-3.1.1.min.js")"></script>
<script src="#Url.Content("~/Scripts/jquery.signalR-2.2.1.min.js")"></script>
<script src="#Url.Content("~/signalr/hubs")"></script>
<script>
$(function () {
var counterHub = $.connection.counterHub;
$.connection.hub.start().done(function () {
});
counterHub.client.UpdateCount = function (count) {
$("#counter").text(count);
}
});
</script>
The hub class :
public class CounterHub : Hub
{
static long counter = 0;
public override System.Threading.Tasks.Task OnConnected()
{
counter = counter + 1;
Clients.All.UpdateCount(counter);
return base.OnConnected();
}
public override System.Threading.Tasks.Task OnDisconnected(bool stopCalled)
{
counter = counter - 1;
Clients.All.UpdateCount(counter);
return base.OnDisconnected(stopCalled);
}
//public void Hello()
//{
// Clients.All.hello();
//}
}
And the Startup.cs :
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
ConfigureAuth(app);
}
}
Not sure why, but this made it work for me finally. I just surrounded the script tags with #section scripts :
#section scripts{
<script src="~/Scripts/jquery.signalR-2.2.1.min.js"></script>
<script src="~/signalr/hubs"></script>
<script>
$(function () {
var myHub = $.connection.counterHub;
$.connection.hub.start().done(function () {
});
myHub.client.UpdateCount = function (count) {
$("#counter").text(count);
}
});
</script>
}
Is your chat files in the root of application?
The only thing that I think is your page has not connected to Hub proxy javascript file:
ASP.NET SignalR JavaScript Library v1.0.0
This file has some methods to connect to hub, consists:
$.hubConnection.prototype.createHubProxies = function () {
var proxies = {};
this.starting(function () {
// Register the hub proxies as subscribed
// (instance, shouldSubscribe)
registerHubProxies(proxies, true);
this._registerSubscribedHubs(); .......
That lack of this method caused your error:
Cannot read property 'counterHub' of undefined
Because it can not connect to hob and create objec named counterHub.
So please test this: After loading your application in another tab of your browser test this url:
Your-App-Url/signalr/hubs
That in local host is some thing like this:
http://localhost:53398/signalr/hubs
And see if you get the javascript file or not. If not I suggest you to start another project(If it is test).

SignalR chat not connecting to the Hub?

I am trying to create a signalr chatroom in asp.net I am getting the following error "Uncaught TypeError: Cannot read property 'chatHub' of undefined" and the prompt does not come up.
I followed this tutorial https://www.asp.net/signalr/overview/getting-started/tutorial-getting-started-with-signalr with a modification to the startup class.
Startup.cs..
using Microsoft.AspNet.SignalR;
using Microsoft.Owin;
using Owin;
[assembly: OwinStartupAttribute(typeof(MyTrainer.Startup))]
namespace MyTrainer
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
var config = new HubConfiguration();
config.EnableDetailedErrors = true;
config.EnableJavaScriptProxies = true;
app.MapSignalR("/signalr", config);
}
}
}
My View (ChatRoom.cshtml)...
#{
ViewBag.Title = "ChatRoom";
}
<!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>
<!--Script references. -->
<!--Reference the jQuery library. -->
<script src="../Scripts/jquery-1.11.3.min.js"></script>
<!--Reference the SignalR library. -->
<script src="../Scripts/jquery.signalR-2.2.1.min.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">
$(function () {
// Declare a proxy to reference the hub.
var chat = $.connection.chatHub;
// Create a function that the hub can call to broadcast messages.
chat.client.broadcastMessage = function (name, message) {
// Html encode display name and message.
var encodedName = $('<div />').text(name).html();
var encodedMsg = $('<div />').text(message).html();
// Add the message to the page.
$('#discussion').append('<li><strong>' + encodedName
+ '</strong>: ' + encodedMsg + '</li>');
};
// Get the user name and store it to prepend to messages.
$('#displayname').val(prompt('Enter your name:', ''));
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
});
</script>
</body>
</html>
My Hub...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
namespace MyTrainer
{
public class ChatHub : Hub
{
public void Send(string name, string message)
{
Clients.All.broadcastMessage(name, message);
}
}
}
My Controller..
public ActionResult ChatRoom()
{
return View();
}
Thank you!
I was rendering fullcalendar scripts in the layout page that was messing with the scripts for signal r
You should catch the error message when connecting to the server,you can add ".fail", one of the errors you may encounter is due to the version.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
}).fail(function (reason) {
console.log("SignalR connection failed: " + reason);
});

SignalR proxy is undefined

why $.connection.connectionhub is undefined, am using webform.
<script src="/scripts/jquery-1.6.4.min.js" "></script>
<!--Reference the SignalR library. -->
<script src="/scripts/jquery.signalR-2.2.1.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="/signalr/signalr/hubs"></script>
<!--Add script to update the page and send messages.-->
<script type="text/javascript">
$(function () {
$.connection()
// why it is undefined
var chat = $.connection.connectionhub;
---------------------------Hub Class------------------------------
public class ConnectionHub : Microsoft.AspNet.SignalR.Hub
{
public void Hello()
{
Clients.All.hello();
}
public void SendMessage()
{
}
}
------------------------Scripts----------------------------------
I have found the solution, but am not satisfy what is the behavior of this code? any one can elaborate it?
when I write below code it works fine
var hubb = $.connection.connectionHub;
when I write the code
//only h is small it can't work
var hubb = $.connection.connectionhub;
can any one explain logic here??
snap shot of code

Categories