Cannot read property 'counterHub' of undefined - javascript

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).

Related

SignalR 2.3 cannot read property client

Good day,
Unfortunately, I can not get SignalR to work for a private 1 on 1 chat.
Here the following things that I have done:
References that are situated in the head tag of my layout page in the right order:
<script src="~/Scripts/jquery-1.6.4.min.js"></script>
<script src="~/Scripts/jquery.signalR-2.3.0.js"></script>
Even added both bellow to check if either worked but no luck.
<script src="/signalr/hubs"></script>
<script src="http://localhost:50581/signalr/hubs"></script>
Have an Owin startup class:
[assembly: OwinStartup(typeof(Startup))]
namespace WebApplication6
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
var config = new HubConfiguration();
config.EnableDetailedErrors = true;
config.EnableJavaScriptProxies = true;
app.MapSignalR("/signalr", config);
}
}
}
Have my chatHub class with my methods inside:
[HubName("chatHub")]
public class ChatHub : Hub
{
}
I have a javascript file named chatboxManager with the following inside:
var connection = $.hubConnection();
var ChatHub = connection.createHubProxy('chatHub');
Using the above I get a connection to the chatHub
but it does not recognise the .client the bellow:
// On New User Connected
debugger;
ChatHub.client.onNewUserConnected = function (id, name, userid) {
AddUser(ChatHub, id, name, userid);
}
If I use this at the beginning of the js file nothing works:
var ChatHub = $.connection.chatHub;
Is there something else that I could be missing?
I have de-installed the packages and re-installed them.
Any advice would greatly be appreciated to get this running.
Kind regards and thanks
I dont know if this might be the solution but give it a try
var hubConnection = new HubConnection("http://yourIpHere:yourPortNr/signalr");
var chatHubProxy = hubConnection.CreateHubProxy("chatHub");

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

Callback on client does not get triggered with SignalR

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 }));
}

Recaptcha.create works locally but not on server

I've got an Google Recaptcha it uses the Recaptcha.create. However for some reason the Recaptcha.create works locally but not on the server. Here is my html and js.
HTML
<script type="text/javascript" src="http://www.google.com/recaptcha/api/js/recaptcha_ajax.js"></script>
<div id="recaptcha"></div>
<div id="fError">Waiting for input.</div>
<script src="/assets/js/upload-flash.js"></script>
And this is the upload-flash.js
var captchaused = false;
function showRecaptcha() {
Recaptcha.create("6LfHYvgSAAAAAJ9G7fNYW5vwQkxUZDNSFhweiOPp", "recaptcha", {
theme: "clean",
callback: Recaptcha.focus_response_field});
}
function fileSelected() {
var file = document.getElementById('fileToUpload').files[0];
if (file) {
if(captchaused === false){
captchaused = true;
showRecaptcha();
} else {
Recaptcha.reload();
}
}
}
/*... and after this comes the uploading part. Removed it so that it doesn't become too long*/
Here are pictures
Local
Server
I made a mistake with the public and private keys I get from google and used the wrong ones. After changing the keys I used it started working perfectly again.

Play Framework 2.1 websockets in Chrome

I can't seem to get websocket communication to work in the Play Framework version 2.1.
I created a simple test that does nothing but send messages back and forth with a push of a button. All the code for it is below. But nothing shows up except for the button.
Has anybody seen this problem or can someone tell me what I may be doing wrong in the code below?
I am using the latest version of Chrome.
Here is my simple setup.
In Application.java
public static Result index() {
return ok(index.render());
}
public static WebSocket<String> sockHandler() {
return new WebSocket<String>() {
// called when the websocket is established
public void onReady(WebSocket.In<String> in,
WebSocket.Out<String> out) {
// register a callback for processing instream events
in.onMessage(new Callback<String>() {
public void invoke(String event) {
System.out.println(event);
}
});
// write out a greeting
out.write("I'm contacting you regarding your recent websocket.");
}
};
}
In Routes File
GET / controllers.Application.index()
# Map static resources from the /public folder to the /assets URL path
GET /assets/*file controllers.Assets.at(path="/public", file)
GET /greeter controllers.Application.sockHandler()
In Index.Scala.html
#main(null) {
<div class="greeting"></div>
<button class="send">Send</button>
<script type="text/javascript" charset="utf-8">
$(function() {
var WS = window['MozWebSocket'] ? MozWebSocket : WebSocket
var sock = new WS("#routes.Application.sockHandler()")
sock.onmessage = function(event) {
$('.greeting').append(event.data)
}
$('button.send').click(function() {
sock.send("I'm sending a message now.")
});
})
</script>
}
In Main.scala.html
#(title: String)(content: Html)
<!DOCTYPE html>
<html>
<head>
<title>#title</title>
<link rel="stylesheet" media="screen" href="#routes.Assets.at("stylesheets/main.css")">
<link rel="shortcut icon" type="image/png" href="#routes.Assets.at("images/favicon.png")">
<script src="#routes.Assets.at("javascripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
</head>
<body>
#content
</body>
The problem is in
var sock = new WS("#routes.Application.sockHandler()")
you have to specify the protocol and the complete url in the format: ws://localhost:9000/greeter.
Check this question to do it in javascript: How to construct a WebSocket URI relative to the page URI?
you can use a Route's webSocketURL() method to retrieve a url that can be passed to a WebSocket's constructor. Here's an example from Play's websocket-chat sample code:
$(function() {
var WS = window['MozWebSocket'] ? MozWebSocket : WebSocket
var chatSocket = new WS("#routes.Application.chat(username).webSocketURL()")
var sendMessage = function() {
chatSocket.send(JSON.stringify(
{text: $("#talk").val()}
))
$("#talk").val('')
}
// ...
So in your code you can use something like
var sock = new WS("#routes.Application.sockHandler().webSocketURL()");
Personally I don't like intermingling interpolated code with JS, since I think that any code executing on the client should only be concerned with the state of the client, and not the server (not to mention it makes refactoring the script out into an external file impossible), so I tend to do something like this:
<div class="container app-container"
data-ws-uri="#routes.Application.WSUri.webSocketURL()">
.......
</div>
Then in my JS I can just do something like
var sock = new WS(document.querySelector(".app-container").dataset.wsUri);
// ....

Categories