Connecting Client Server in ASP.net MVC Signal R - javascript

This is my Signal R Client.
I get this error when i run my client.(0x800a139e - JavaScript runtime error: SignalR: Error loading hubs. Ensure your hubs reference is correct, e.g. .)
The exception comes from line $.connection.hub.start
There is a ServerHub class in a folder HUBS in my Server application which runs fine.
Can anyone help me out..
Thanks
<script src="~/Scripts/jquery.signalR-2.2.0.min.js"></script>
<script src="http://localhost:39670/MySignalRServer/signalr/hubs"></script>
var ChatHubProxy = $.hubConnection("http://localhost:39670/MySignalRServer/signalr/hubs");
var chat = ChatHubProxy.createHubProxy('ServerHub');
chat.on("addNewMessageToPage",function (name, message) {
// Add the message to the page.
$('#discussion').append('<li><strong>' + htmlEncode(name)
+ '</strong>: ' + htmlEncode(message) + '</li>');
});
$.connection.hub.start({jsonp:true}).done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('#displayname').val(), $('#message').val());
alert("hiii");
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});

Try change your code to :
<script src="~/Scripts/jquery.signalR-2.2.0.min.js"></script>
<script src="http://localhost:39670/MySignalRServer/signalr/hubs"></script>
var chat = $.connection.ServerHub; //here
chat.on("addNewMessageToPage", function(name, message) {
// Add the message to the page.
$('#discussion').append('<li><strong>' + htmlEncode(name)
+ '</strong>: ' + htmlEncode(message) + '</li>');
});
$.connection.hub.start().done(function() { //here
$('#sendmessage').click(function() {
// Call the Send method on the hub.
chat.server.send($('#displayname').val(), $('#message').val());
alert("hiii");
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
And make sure that this address is good - <script src="http://localhost:39670/MySignalRServer/signalr/hubs"></script>
I always use this - <script src="/signalr/hubs"></script>
And add HubName Attribute
[HubName("ServerHub")]
public class ServerHub : Hub
{
public string Send(string name, string message)
{
Clients.All.broadcastMessage(name, message);
return null;
}
}
or change this code :
var chat = $.connection.ServerHub;
to
var chat = $.connection.serverHub;
Demo project : https://github.com/czerwonkabartosz/SignalRDemo

Related

Display SignalR message with embedded HTML

I've begun playing around with SignalR, of course starting with the initial chat hub that I suppose everybody does at one point or another. I want to modify it so that if the user types in HTML in their message, when it gets displayed it shows rendered HTML as oppose to just the string with HTML tags in it.
Here is my javascript:
<script type="text/javascript">
$(function () {
var chat = $.connection.chatHub;
chat.client.broadcastMessage = function (name, message) {
var encodedName = $('<div />').text(name).html();
var encodedMesg = $('<div />').text(message).html();
if (message === "joined session") {
$('#discussion').append('<li><strong>' + encodedName + ' ' + encodedMesg + '</strong></li>');
} else {
$('#discussion').append('<li><strong>' + encodedName + '</strong>: &nbsp' + encodedMesg + '</li>');
}
};
$('#message').focus();
$.connection.hub.start().done(function () {
chat.server.send("#FullName", "joined session");
$('#sendmessage').click(function () {
chat.server.send("#FullName", $('#message').val());
$('#message').val("").focus();
});
});
});
The encodedMesg has "this is <b>bold</b>", but instead of rendering it as HTML, it just shows it as a string. How can I allow this to render as HTML?
I've tried encoding the < as < and > as > but that didn;t work. I also tried %3C and %3E but they didn;t work either.
Calling .text changes the text of an object and intentionally prevents html or scripts from being parsed.
You can get it to parse it by changing the value with .html
var encodedMesg = $('<div />').html(message);
use this:
var encodedMsg = $('').text(message).html();

Calling flash notification via JS

The base rails app has flash messages that can be called via:
"flash.now[:error]"
However, how do I call it manually via JS? Here is my current code:
var show_error = function (message) {
$("#flash-messages").html('<div class="flashes"> <div class="flash-notice">' + message + '</div> </div>');
return false;
};
You can set a default message by including it in the function. Read more about JS || here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_OR_()
You may also want to see this answer SO: Best practice method of displaying flash messages
var show_error = function (message) {
message = message || 'Something should be flashing here!';
$("#flash-messages").html('<div class="flashes"> <div class="flash-notice">' + message + '</div> </div>');
return false;
};
/*
show_error();
*/
/*
show_error('Something is Flashing!');
*/

Send a variable from a JavaScript script inside my ASP.NET page to a C# Function in Code-Behind [duplicate]

This question already has an answer here:
How to set a C# variable value from javascript
(1 answer)
Closed 7 years ago.
I have my ASP.NET C# Web site and i have some JavaScript script inside one of my pages, i already succeeded in calling a C# function from my Code Behind but i want to send some variable from my JavaScript script as an argument of the function.
Here is my code, including the C# function call:
<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();
var tremp_id = $('<div /> ').text("<%=Request.QueryString["trempid"]%>").html();
// Add the message to the page.
$('#discussion').append('<li class="<%=returnLiClass()%><strong>' + encodedName
+ '</strong>: ' + encodedMsg + "Tremp:" + tremp_id + '</li>');
};
// Get the user name and store it to prepend to messages.
$('#displayname').val('<%=returnName()%>');
// 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>
As you can see I'm calling the 'returnLiClass()' function (line 13) and i want to send the 'encodedMsg' var inside it.
How can i do it? Thanks!
Place a function with name same as client method in your Hub class.
void broadcastMessage(string name, string message)
{
//Do something here.....
}
Please note that the parameter name must be same.

Communication with the server side is not working - node.js

I'm kind of new using node.js. I'm using express with jQuery and mySQL.
I'm trying to add a record in to the db by filling 2 fields in the UI and then call a server via getJSON to add the record. I'm giving the details into the url.
This is not working.
Here is a snippet from the code (I adjust it and eliminate all the checks to make it short)
client side
$("#btnAddEvent").click( function() {
// Send details to the server to add a record to the db
var url2Send = '/insert/title/' + $("#Title").val() + '/desc/' +
$("#Desc").val()
$.getJSON( url2Send, function( data ) {
$("#Title").empty();
$("#Desc").empty();
});
});
}
Server side
router.get('/insert/title/:t/desc/:d', function(req, res) {
var qry = "insert into events (evt_title, evt_desc) " +
"values (\'" + req.params.t + "\',\'" + req.params.d + "\')";
app.connection.query( qry, function(err, qry_res) {
if (err) {
console.log( 'Error: ' + err );
return false;
}
else {
console.log( 'Event added .....' );
res.json(dd);
return true;
}
});
});
When I run and try to go through this code, it doesn't succeed and display the homepage instead. In the server console it shows it's trying to get the following
GET /?add_event_title=lkjhkjhkj&add_event_desc=kjhkjhkj 200 306.584 ms - 19709
add_event_title and add_event_desc are the IDs of the UI fields in the form used to define the db fields evt_title and evt_desc respectively.
Any explanation for this please? Any way to make the communication smooth?
Thanks

include socket.io server into my html

I have run my nodeServer and Client sucessfully. But I want to connect its server to a proxy.
Here is the node client:
<html>
<head>
<script src="http://localhost:8000/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
<script>
var name = '';
var socket = io.connect('http://localhost:8000');
// at document read (runs only ones).
$(document).ready(function(){
// on click of the button (jquery thing)
// the things inside this clause happen only when
// the button is clicked.
$("button").click(function(){
// just some simple logging
$("p#log").html('sent message: ' + $("input#msg").val());
// send message on inputbox to server
socket.emit('chat', $("input#msg").val() );
// the server will recieve the message,
// then maybe do some processing, then it will
// broadcast it again. however, it will not
// send it to the original sender. the sender
// will be the browser that sends the msg.
// other browsers listening to the server will
// recieve the emitted message. therefore we will
// need to manually print this msg for the sender.
$("p#data_recieved").append("<br />\r\n" + name + ': ' + $("input#msg").val());
// then we empty the text on the input box.
$("input#msg").val('');
});
// ask for the name of the user, ask again if no name.
while (name == '') {
name = prompt("What's your name?","");
}
// send the name to the server, and the server's
// register wait will recieve this.
socket.emit('register', name );
});
// listen for chat event and recieve data
socket.on('chat', function (data) {
// print data (jquery thing)
$("p#data_recieved").append("<br />\r\n" + data.msgr + ': ' + data.msg);
// we log this event for fun :D
$("p#log").html('got message: ' + data.msg);
});
</script>
</head>
<body>
<input type="text" id="msg"></input><button>Click me</button>
<p id="log"></p>
<p id="data_recieved"></p>
</body>
</html>
Here is Server:
var check="check";
var io = require('socket.io').listen(8000);
// open the socket connection
io.sockets.on('connection', function (socket) {
// listen for the chat even. and will recieve
// data from the sender.
console.log('hello nahid');
socket.on('chat', function (data) {
// default value of the name of the sender.
var sender = 'unregistered';
check=sender;
// get the name of the sender
socket.get('nickname', function (err, name) {
console.log('Chat message by ', name);
console.log('error ', err);
sender = name;
});
// broadcast data recieved from the sender
// to others who are connected, but not
// from the original sender.
socket.broadcast.emit('chat', {
msg : data,
msgr : sender
});
});
// listen for user registrations
// then set the socket nickname to
socket.on('register', function (name) {
// make a nickname paramater for this socket
// and then set its value to the name recieved
// from the register even above. and then run
// the function that follows inside it.
socket.set('nickname', name, function () {
// this kind of emit will send to all! :D
io.sockets.emit('chat', {
msg : "naay nag apil2! si " + name + '!',
msgr : "mr. server"
});
});
});
});
They work well together. Now I want to have included server file into another html client like this:
<script type="text/javascript" src="nodeServer.js"></script>
In order to access variables in nodeServer.js. But The error "Uncaught ReferenceError: require is not defined "
What can I do to solve this and also I have this line code :
such that it knows what socket.io syntax is. But the error exists.
What should I do to make my html file know socket.io.js.
EDIT:
The last comment on the checked answer is what solved my issue. Thanks to #Houseman.
I'm pretty sure you can't just throw a Node.js file into a html DOM and expect it to work. Node.js files are run by Node.js, not by client-side html javascript.
This line <script src="http://localhost:8000/socket.io/socket.io.js"></script> is sufficient for loading the io object into your DOM, and make it accessible through javascript.
Remove this line:
<script type="text/javascript" src="nodeServer.js"></script>
, and you should be fine, if your server is running on port 8000. Your server code, however, doesn't seem to have the necessary components to actually run.
EDIT:
If you want to pass variables from your client to your server, or the other way around, use sockets, just like you're already doing.

Categories

Resources