JavaScript sending data back to same window using callback - javascript

I have a opened window called "http://192.168.17.109/report3_test/post-data" shown below.
Onclick Launch button I am passing textbox id and callback function here is the html and jquery function
HTML
<form id="report">
<div class="form-group">
<center><label for="post-data"><h3>Reporting Data</h3></label></center>
<textarea class="form-control" rows="20" id="post-data" name="post-data"></textarea>
</div>
<div class="form-group">
<div class="col-sm-6"><button type="submit" class="btn btn-primary btn-block" name="launch" id="launch" onclick="invoke_reporting(document.getElementById('post-data'),callback)">Launch</button>
</div>
</div>
</form>
JavaScript
function invoke_reporting(textdata,callback) {
window.open("http://192.168.17.109/report3_test/templates/ct-head");
if (callback && typeof(callback) === "function") {
callback(textdata,newwindow);
}
}
Here I am opening a this new window on click launch and it shown below http://192.168.17.109/report3_test/templates/ct-head
Onclick copy to clipboard button I want to send data back to already opened window shown on top that is "http://192.168.17.109/report3_test/post-data" and here is my callback method .
function callback(finaldata){
var arr = $.parseHTML(finaldata);
v
Window.onload = function(){
var test_data = "";
for(var i=0; i<finaldata.length;i++)
{
if(i == 0){
var first_element = 'REPORT TITLE:' + '<br/>' + finaldata[0] + '<br/>' + '<br/>';
test_data += first_element.replace(/<br.*?>/g, '\n');
}else if(i == 1){
var second_element = 'FINDINGS:' + '<br/>' + finaldata[1] + '<br/>' + '<br/>';
test_data += second_element.replace(/<br.*?>/g, '\n');
}else{
var final_element = 'IMPRESSION:' + '<br/>' + finaldata[2];
test_data += final_element.replace(/<br.*?>/g, '\n');
}
}
newWindow.document.getElementById('post-data').value = test_data;
};
}
Any help would be appreciated.

Related

Trying to get the HTML displayed to change every time a new button is clicked with jquery

let table = 6;
let i = 1;
$(function() {
let $newOperatorButton = $('button');
$newOperatorButton.on('click', function math(){
let msgOperator = '';
let expression;
let operator = $(this).attr("value");
if(operator === '+'){
msgOperator = ' + ';
expression = (table + i);
while(i < 11){
msg += table + msgOperator + i + ' = ' + (table + i) + '<br />';
i++;
}
} else if (operator === '-') {
msgOperator = ' - ';
expression = (table - i);
while(i < 11){
msg += table + msgOperator + i + ' = ' + (table - i) + '<br />';
i++;
}
some code missing but it adds multiplication and division
let el = document.getElementById('blackboard');
el.innerHTML = msg;
}
);
});
This code is inside the body tag in my index.html
<section id="page">
<section id="blackboard"></section>
</section>
<form id="operator">
<button name="add" type="button" value="+">+</button>
<button name="subtract" type="button" value="-">-</button>
<button name="multiply" type="button" value="x">x</button>
<button name="division" type="button" value="/">/</button>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="/index.js"></script>
I have it so it prints out a table with 10 numbers depending on the button clicked. For ex. table = 6 and i = 1 is 6+1=7.... 6+10=16
You need an if statement at the end that reset your equations and variables.
after you've run your equation "i" is still equal to 11 so it never passes into the while loops again, you also need to empty your message so it doesn't keep adding addition text to your existing text.
$("#blackboard").html(msg)
if (i == 11) {
i = 1
msg = ""
}

I cannot add the class "unread" to the append content of a certain data-id

I want to add the "unread" class to an append content with a specific data-id. The following line of code works fine in the browser console. However, when the code is run it does not add the class "unread".
var idMessage = message[message.length-1].id;
$('#visitors').find('h5[data-id=' + idMessage + ']').addClass('unread');
The goal is to add "unread" in the following line of code:
$("#visitors").append('<h5 class="' + state + '" data-id=' + visitors[i].idSession + '>' + visitors[i].visitorOnline + '</h5>');
I will provide you with a code snippet
<div id="conexion-chat">
<button id="btn-conexion-chat" onclick="initWebSocket();">Iniciar chat</button>
</div>
<div id="display-chat" style="display: none;">
<div id="visitors"></div>
<br />
<textarea id="chatRoomField" rows="10" cols="30" readonly></textarea> <br/>
<input id="sendField" value="" type="text">
<button id="sendButton" onclick="send_message();">Enviar</button>
</div>
function initWebSocket(){
$('#conexion-chat').css('display', 'none');
$('#display-chat').css('display', '');
websocket = new WebSocket("ws://localhost:8080/o/echo");
websocket.onopen = function (event) {
websocket.send(json_user());
};
websocket.onclose = function(event) {
localStorage.clear();
console.log("DESCONECTADO");
};
websocket.onmessage = function(event) {
var message = event.data;
processMessage(message);
};
websocket.onerror = function(event) {
console.log("ERROR: " + event.data);
};
}
function visitorSelected(event){
var visitorSelected = $(event.target).data('id');
localStorage.setItem('visitorSelected', visitorSelected);
websocket.send(json_messages(visitorSelected, '${email}', '${read}'));
document.getElementById("chatRoomField").innerHTML = "";
}
function processMessage(message){
if(message == '${disconnected}'){
document.getElementById("chatRoomField").innerHTML += "El patrocinador no se encuentra conectado." + "\n";
}else {
var json_message = JSON.parse(message);
var visitorSelected = localStorage.getItem('visitorSelected');
if(json_message.hasOwnProperty('message') && message.length > 0){
var message = json_message.message;
var text = "";
if('${currentUserRol}' != '${rolPreferences}'){
for(var i=0; i<message.length; i++){
text += message[i].from + ": " + message[i].message + "\n";
document.getElementById("chatRoomField").innerHTML = text;
}
}else{
if(message[message.length-1].id == visitorSelected || message[message.length-1].idTo == visitorSelected){
for(var i=0; i<message.length; i++){
text += message[i].from + ": " + message[i].message + "\n";
document.getElementById("chatRoomField").innerHTML = text;
}
}else{
var idMessage = message[message.length-1].id;
$('#visitors').find('h5[data-id=' + idMessage + ']').addClass('unread');
}
}
}
if(json_message.hasOwnProperty('visitors') && json_message.visitors.length > 0){
var visitors = json_message.visitors;
var state;
$("#visitors h5").remove();
for (var i = 0; i < visitors.length; i++) {
state = (visitors[i].idSession == visitorSelected)? "selected" : "not-selected";
$("#visitors").append('<h5 class="' + state + '" data-id=' + visitors[i].idSession + '>' + visitors[i].visitorOnline + '</h5>');
}
if(visitorSelected == null){
$("#visitors h5:first-child").attr("class", "selected");
visitorSelected = $("#visitors h5:first-child").attr("data-id");
localStorage.setItem('visitorSelected', visitorSelected);
}
}
}
}
$('#visitors').on('click', 'h5.not-selected', visitorSelected);
*Note: The entire code has not been submitted, but a code snippet.
Thanks!
Regards!

how to build dynamic form builder with jquery

I want to develop a dynamic form builder with jquery where users can build their own form and change form name, input type, size etc. I know there are some cool drag and drop online form builders but i want to develop a very simple form builder .
I already have started to develop this and i am facing some issues.
when user will click on the label(input field) it create an input field dynamically with jquery with edit and delete button.
The code below is appending input field in a div which is empty right now.
$(document).ready(function() {
$(".text").click(function(){
$("#textInput").append('<input class="form-control" type="text">' + '<input class="btn btn-default" type="button" value="Edit" id="editbtn"><input class="btn btn-default" type="button" value="Delete" >' ).show().css('display', 'block')});
});
.items {
border: 1px solid lightgray;
display: none;
padding: 0 10px 10px 10px;
}
<div class="items" id="textInput">
<h3>Your Form</h3>
<hr>
</div>
On clicking the text input i want to display a table or modal where user can save changes to input field first of all the edit button is not working and secondly how to edit and save changes to input field(how the process will work).
This is what i want to achieve
I have been working on dynamic form builder and borrowed ideas from some excellent open-source solutions.
They do it in this way:
describe form structure as JSON in the backend.
then use one of the following libraries to render JSON to form in the frontend.
jsonform/jsonform
source code: jsonform/jsonform
example:
rjsf-team/react-jsonschema-form
source code: https://github.com/rjsf-team/react-jsonschema-form
I'd suggest you to look at schema-to-form libraries (for example some of those described in here How to Create a form from a json-schema?).
There are multiple benefits of using such libraries, some of which are flexible layout capabilities, as well as validation hooks.
What is more, your editor has to work with JSON structure only and rendering a form from it is not your main headache.
I did this using JQuery, HTML and Bootstrap
the form was built to be as dynamic as possible and built also to me modified
there is a script to submit the form via ajax
function d(object) {
const id = $(object).data('check');
$('#' + id).remove();
}
//picks and submits form inputs
$(document).ready(function() {
$('form.myForm').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
}
});
return false;
});
});
$(function() {
//here i will populate the appendi field if the user selects file
//the user should select the file type
$('#type').on('change', function() {
let type = $("#type option:selected").val();
var add;
if (type === 'file') {
//here i will append the new option in the appendi part
add = "<label for=\"\">What type of file?</label>";
add += "<select name=\"image_type\" id=\"\" class=\"form-control\">";
add += "<option value=\"all\">All</option>";
add += "<option value=\"image\">Image</option>";
add += "<option value=\"document\">Document</option>";
add += "</select>";
$('#appendi').html(add);
}
if (type === 'radio' || type === 'checkbox') {
//here i will append the new option in the appendi part
add = "<label for=\"\">Enter the names of the option separated by a comma (,)</label>";
add += "<textarea col=\"\" class=\"form-control\" row=\"\" name=\"options\" required></textarea>";
$('#appendi').html(add);
}
if (type === 'paragraph' || type === 'text') {
$('#appendi').empty();
}
})
})
$(document).ready(function() {
$('form.myInput').on('submit', function() {
var that = $(this),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
addBody(data);
return false;
});
});
function addBody(data) {
//first thing first is to generate an outer shell
let id_tag = "shell_" + generateId(8);
let shell1_open = "<div class='form-group' " + "id = '" + id_tag + "'>";
shell1_open += "<button type='button' onclick='d(this)' id=\"delete\" data-check='" + id_tag + "'><i class=\"fa-minus-square\">remove</i></button>"
let shell1_close = "</div>";
let shell2, label, shell2_close;
if (data.type === 'text' || data.type === 'date' || data.type === 'file' || data.type === 'email') {
shell2 = "<input type='";
shell2 += data.type + "'";
shell2_close = ">";
}
if (data.type === 'paragraph') {
shell2 = "<textarea";
shell2_close = "></textarea>";
}
if (data.type === 'radio') {
let myArr = data.options.split(",");
shell2 = '';
let name = 'input_' + generateId(5) + '_' + data.name.replace(/\s+/g, '');
for (let i = 0; i < myArr.length; i++) {
shell2 += "<input type='radio'";
shell2 += "value ='" + myArr[i] + "'";
shell2 += "name ='" + name + "'";
//add a class to it
shell2 += " class = 'form-control'";
if (data.required === 'yes') {
shell2 += " required";
}
shell2 += ">" + myArr[i];
}
shell2_close = "";
}
if (data.type === 'checkbox') {
let myArr = data.options.split(",");
shell2 = '';
for (let i = 0; i < myArr.length; i++) {
shell2 += "<input type='checkbox'";
shell2 += "value ='" + myArr[i] + "'";
shell2 += " name='" + 'input_' + generateId(5) + '_' + data.name.replace(/\s+/g, '') + "'";
//add a class to it
shell2 += " class = 'form-control'";
if (data.required === 'yes') {
shell2 += " required";
}
shell2 += ">" + myArr[i];
}
shell2_close = "";
}
if (data.image_type) {
if (data.image_type === 'all') {
shell2 += " accept";
}
if (data.image_type === 'image') {
shell2 += " accept='.jpeg, .png'";
}
if (data.image_type === 'document') {
shell2 += " accept='.pdf, .xls, .docx'";
}
}
if (data.type !== 'radio' && data.type !== 'checkbox') {
if (data.required === 'yes') {
shell2 += " required";
}
/**
* after thinking i decided to map the name the user chose to the placeholder/label
* and squash the name to get the input name, so to remove whitespaces
* also i'll append input_ to all input names
*/
shell2 += " name='" + 'input_' + generateId(5) + '_' + data.name.replace(/\s+/g, '') + "'";
//add a class to it
shell2 += " class = 'form-control'";
//add placeholder
shell2 += " placeholder = '" + data.name + '\'';
}
$('#main-form-body').append(shell1_open + shell2 + shell2_close + shell1_close)
//console.log(shell1_open + shell2 + shell2_close +shell1_close);
}
function dec2hex(dec) {
return dec.toString(16).padStart(2, "0")
}
// generateId :: Integer -> String
function generateId(len) {
var arr = new Uint8Array((len || 40) / 2)
window.crypto.getRandomValues(arr)
return Array.from(arr, dec2hex).join('')
}
<html>
<head>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
</head>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
Add input
</button>
<form action="" method="post" class="myForm">
<div id="main-form-body">
</div>
<button type='submit'>Submit</button>
</form>
<!-- The Modal -->
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Add form input</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<form action="" method="get" class="myInput">
<!-- Modal body -->
<div class="modal-body">
<div class="form-group">
<label for="">What should this be called?</label>
<input type="text" name="name" class="form-control">
</div>
<div class="form-group">
<label for="">What type of data will it hold?</label>
<select name="type" id="type" class="form-control">
<option value="text">Text</option>
<option value="paragraph">Paragraph</option>
<option value="file">File</option>
<option value="radio">Radio</option>
<option value="checkbox">Checkbox</option>
<option value="date">Date</option>
</select>
</div>
<div class="form-group" id="appendi">
</div>
<div class="form-group">
<label>Should it be a required field?</label>
<select name="required" id="" class="form-control">
<option value="yes">yes</option>
<option value="no">no</option>
</select>
</div>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Add</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
</html>
enter image description hereYou can use this form builder..
it's available in github
https://github.com/vimal33329/Formbuilder
live url link
https://vimal33329.github.io/Formbuilder/
if you already familiar with github use git clone below code
https://github.com/vimal33329/Formbuilder.git
or download source file by clicking below link...
https://github.com/vimal33329/Formbuilder/archive/refs/heads/main.zip
Form with report
Create form, Build form, Enable or disable Form Submission, Dynamic Option creating,
View Form Report in report page, Drag and Drop position changing...
https://vimal-form.herokuapp.com
enter image description here
enter image description here
enter image description here
enter image description here

.replacewith not working when called a second time

I have the following markup:
<fieldset>
<legend>Headline Events...</legend>
<div style="width:100%; margin-top:10px;">
<div style="width:100%; float:none;" class="clear-fix">
<div style="width:400px; float:left; margin-bottom:8px;">
<div style="width:150px; float:left; text-align:right; padding-top:7px;">
Team Filter:
</div>
<div style="width:250px; float:left;">
<input id="teamFilter" style="width: 100%" />
</div>
</div>
<div style="width:400px; float:left; margin-bottom:8px;">
<div style="width:150px; float:left; text-align:right; padding-top:7px;">
Type Filter:
</div>
<div style="width:250px; float:left;">
<input id="typeFilter" style="width: 100%" />
</div>
</div>
</div>
</div>
<div id="diaryTable" name="diaryTable" class="clear-fix">
Getting latest Headlines...
</div>
</fieldset>
I also have the following scripts
<script>
function teamFilterChange(e) {
//alert(this.value());
setCookie('c_team', this.value(), 90);
$c1 = getCookie('c_team');
$c2 = getCookie('c_type');
var param = "true|" + $c1 + "|" + $c2;
outputHLDiaryEntries(param);
}
function typeFilterChange(e) {
//alert(this.value());
setCookie('c_type', this.value(), 90);
$c1 = getCookie('c_team');
$c2 = getCookie('c_type');
var param = "true|" + $c1 + "|" + $c2;
outputHLDiaryEntries(param);
}
// This optional function html-encodes messages for display in the page.
function htmlEncode(value) {
var encodedValue = $('<div />').text(value).html();
return encodedValue;
}
function outputHLDiaryEntries(param) {
var url = "Home/DiaryEntries/";
var data = "id=" + param;
$.post(url, data, function (json) {
var n = json.length;
alert(n + ' ' + json);
if(n == 0){
//json is 0 length this happens when there were no errors and there were no results
$('#diaryTable').replaceWith("<span style='color:#e00;'><strong>Sorry: </strong> There are no headline events found. Check your filters.</span>");
} else {
//json has a length so it may be results or an error message
//if jsom[0].dID is undefined then this mean that json contains the error message from an exception
if (typeof json[0].dID != 'undefined') {
//json[0].dDI has a value so we
//output the json formatted results
var out = "";
var i;
var a = "N" //used to change the class for Normal and Alternate rows
for (i = 0; i < json.length; i++) {
out += '<div class="dOuter' + a + '">';
out += '<div class="dInner">' + json[i].dDate + '</div>';
out += '<div class="dInner">' + json[i].dRef + '</div>';
out += '<div class="dInner">' + json[i].dTeam + '</div>';
out += '<div class="dInner">' + json[i].dCreatedBy + '</div>';
out += '<div class="dType ' + json[i].dType + '">' + json[i].dType + '</div>';
out += '<div class="dServer">' + json[i].dServer + '</div>';
out += '<div class="dComment">' + htmlEncode(json[i].dComment) + '</div></div>';
//toggle for normal - alternate rows
if (a == "N") {
a = "A";
} else {
a = "N";
}
}
//output our formated data to the diaryTable div
$('#diaryTable').replaceWith(out);
} else {
//error so output json string
$('#diaryTable').replaceWith(json);
}
}
}, 'json');
}
$(document).ready(function () {
//Set User Preferences
//First check cookies and if null or empty set to default values
var $c1 = getCookie('c_team');
if ($c1 == "") {
//team cookie does not exists or has expired
setCookie('c_team', 'ALL', 90);
$c1 = "ALL";
}
var $c2 = getCookie('c_type');
if ($c2 == "") {
//type cookie does not exists or has expired
setCookie('c_type', "ALL", 90);
$c2 = "ALL";
}
// create DropDownList from input HTML element
//teamFilter
$("#teamFilter").kendoDropDownList({
dataTextField: "SupportTeamText",
dataValueField: "SupportTeamValue",
dataSource: {
transport: {
read: {
dataType: "json",
url: "Home/SupportTeams?i=1",
}
}
}
});
var teamFilter = $("#teamFilter").data("kendoDropDownList");
teamFilter.bind("change", teamFilterChange);
teamFilter.value($c1);
//typeFilter
$("#typeFilter").kendoDropDownList({
dataTextField: "dTypeText",
dataValueField: "dTypeValue",
dataSource: {
transport: {
read: {
dataType: "json",
url: "Home/DiaryTypes?i=1",
}
}
}
});
var typeFilter = $("#typeFilter").data("kendoDropDownList");
typeFilter.bind("change", typeFilterChange);
typeFilter.value($c2);
// Save the reference to the SignalR hub
var dHub = $.connection.DiaryHub;
// Invoke the function to be called back from the server
// when changes are detected
// Create a function that the hub can call back to display new diary HiLights.
dHub.client.addNewDiaryHiLiteToPage = function (name, message) {
// Add the message to the page.
$('#discussion').append('<li><strong>' + htmlEncode(name)
+ '</strong>: ' + htmlEncode(message) + '</li>');
};
// Start the SignalR client-side listener
$.connection.hub.start().done(function () {
// Do here any initialization work you may need
var param = "true|" + $c1 + "|" + $c2;
outputHLDiaryEntries(param)
});
});
</script>
On initial page load the outputHLDiaryEntries function is called when the signalR hub is started. If I then change any of the dropdownlists this calls the outputHLDiaryEntries but the $('#diaryTable').replaceWith(); does not work. If I refresh the page the correct data is displayed.
UPDATE!
Based on A.Wolff's comments I fixed the issue by wrapping the content I needed with the same element I was replacing... by adding the following line at the beginning of the outputHLDiartEntries function...
var outStart = '<div id="diaryTable" name="diaryTable" class="clear-fix">';
var outEnd = '</div>';
and then changing each of the replaceWith so that they included the wrappers e.g.
$('#diaryTable').replaceWith(outStart + out + outEnd);
replaceWith() replaces element itself, so then on any next call to $('#diaryTable') will return empty matched set.
You best bet is to replace element's content instead, e.g:
$('#diaryTable').html("<span>New content</span>");
I had the same problem with replaceWith() not working when called a second time.
This answer helped me figure out what I was doing wrong.
The change I made was assigning the same id to the new table I was creating.
Then when I would call my update function again, it would create a new table, assign it the same id, grab the previous table by the id, and replace it.
let newTable = document.createElement('table');
newTable.id = "sameId";
//do the work to create the table here
let oldTable = document.getElementById('sameId');
oldTable.replaceWith(newTable);

Getting 0x800a138f - JavaScript runtime error: Unable to get property 'client' of undefined or null reference

I'm making a chat application using SignalR API. I'm getting error as:
0x800a138f - JavaScript runtime error: Unable to get property 'client'
of undefined or null reference
Here is my code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link type="text/css" rel="stylesheet" href="/Css/ChatStyle.css" />
<link rel="stylesheet" href="/Css/JQueryUI/themes/base/jquery.ui.all.css">
<!--Script references. -->
<!--Reference the jQuery library. -->
<script src="/Scripts/jquery-1.8.2.min.js"></script>
<script src="/Scripts/ui/jquery.ui.core.js"></script>
<script src="/Scripts/ui/jquery.ui.widget.js"></script>
<script src="/Scripts/ui/jquery.ui.mouse.js"></script>
<script src="/Scripts/ui/jquery.ui.draggable.js"></script>
<script src="/Scripts/ui/jquery.ui.resizable.js"></script>
<!--Reference the SignalR library. -->
<script src="/Scripts/jquery.signalR-1.0.0.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="/signalr/hubs"></script>
<script type="text/javascript">
$(function () {
setScreen(false);
// Declare a proxy to reference the hub.
var chatHub = $.connection.chatHub;
registerClientMethods(chatHub);
// Start Hub
$.connection.hub.start().done(function () {
registerEvents(chatHub)
});
});
function setScreen(isLogin) {
if (!isLogin) {
$("#divChat").hide();
$("#divLogin").show();
}
else {
$("#divChat").show();
$("#divLogin").hide();
}
}
function registerEvents(chatHub) {
$("#btnStartChat").click(function () {
var name = $("#txtNickName").val();
if (name.length > 0) {
chatHub.server.connect(name);
}
else {
alert("Please enter name");
}
});
$('#btnSendMsg').click(function () {
var msg = $("#txtMessage").val();
if (msg.length > 0) {
var userName = $('#hdUserName').val();
chatHub.server.sendMessageToAll(userName, msg);
$("#txtMessage").val('');
}
});
$("#txtNickName").keypress(function (e) {
if (e.which == 13) {
$("#btnStartChat").click();
}
});
$("#txtMessage").keypress(function (e) {
if (e.which == 13) {
$('#btnSendMsg').click();
}
});
}
function registerClientMethods(chatHub) {
// Calls when user successfully logged in
chatHub.client.onConnected = function (id, userName, allUsers, messages) {
setScreen(true);
$('#hdId').val(id);
$('#hdUserName').val(userName);
$('#spanUser').html(userName);
// Add All Users
for (i = 0; i < allUsers.length; i++) {
AddUser(chatHub, allUsers[i].ConnectionId, allUsers[i].UserName);
}
// Add Existing Messages
for (i = 0; i < messages.length; i++) {
AddMessage(messages[i].UserName, messages[i].Message);
}
}
// On New User Connected
chatHub.client.onNewUserConnected = function (id, name) {
AddUser(chatHub, id, name);
}
// On User Disconnected
chatHub.client.onUserDisconnected = function (id, userName) {
$('#' + id).remove();
var ctrId = 'private_' + id;
$('#' + ctrId).remove();
var disc = $('<div class="disconnect">"' + userName + '" logged off.</div>');
$(disc).hide();
$('#divusers').prepend(disc);
$(disc).fadeIn(200).delay(2000).fadeOut(200);
}
chatHub.client.messageReceived = function (userName, message) {
AddMessage(userName, message);
}
chatHub.client.sendPrivateMessage = function (windowId, fromUserName, message) {
var ctrId = 'private_' + windowId;
if ($('#' + ctrId).length == 0) {
createPrivateChatWindow(chatHub, windowId, ctrId, fromUserName);
}
$('#' + ctrId).find('#divMessage').append('<div class="message"><span class="userName">' + fromUserName + '</span>: ' + message + '</div>');
// set scrollbar
var height = $('#' + ctrId).find('#divMessage')[0].scrollHeight;
$('#' + ctrId).find('#divMessage').scrollTop(height);
}
}
function AddUser(chatHub, id, name) {
var userId = $('#hdId').val();
var code = "";
if (userId == id) {
code = $('<div class="loginUser">' + name + "</div>");
}
else {
code = $('<a id="' + id + '" class="user" >' + name + '<a>');
$(code).dblclick(function () {
var id = $(this).attr('id');
if (userId != id)
OpenPrivateChatWindow(chatHub, id, name);
});
}
$("#divusers").append(code);
}
function AddMessage(userName, message) {
$('#divChatWindow').append('<div class="message"><span class="userName">' + userName + '</span>: ' + message + '</div>');
var height = $('#divChatWindow')[0].scrollHeight;
$('#divChatWindow').scrollTop(height);
}
function OpenPrivateChatWindow(chatHub, id, userName) {
var ctrId = 'private_' + id;
if ($('#' + ctrId).length > 0) return;
createPrivateChatWindow(chatHub, id, ctrId, userName);
}
function createPrivateChatWindow(chatHub, userId, ctrId, userName) {
var div = '<div id="' + ctrId + '" class="ui-widget-content draggable" rel="0">' +
'<div class="header">' +
'<div style="float:right;">' +
'<img id="imgDelete" style="cursor:pointer;" src="/Images/delete.png"/>' +
'</div>' +
'<span class="selText" rel="0">' + userName + '</span>' +
'</div>' +
'<div id="divMessage" class="messageArea">' +
'</div>' +
'<div class="buttonBar">' +
'<input id="txtPrivateMessage" class="msgText" type="text" />' +
'<input id="btnSendMessage" class="submitButton button" type="button" value="Send" />' +
'</div>' +
'</div>';
var $div = $(div);
// DELETE BUTTON IMAGE
$div.find('#imgDelete').click(function () {
$('#' + ctrId).remove();
});
// Send Button event
$div.find("#btnSendMessage").click(function () {
$textBox = $div.find("#txtPrivateMessage");
var msg = $textBox.val();
if (msg.length > 0) {
chatHub.server.sendPrivateMessage(userId, msg);
$textBox.val('');
}
});
// Text Box event
$div.find("#txtPrivateMessage").keypress(function (e) {
if (e.which == 13) {
$div.find("#btnSendMessage").click();
}
});
AddDivToContainer($div);
}
function AddDivToContainer($div) {
$('#divContainer').prepend($div);
$div.draggable({
handle: ".header",
stop: function () {
}
});
////$div.resizable({
//// stop: function () {
//// }
////});
}
</script>
</head>
<body>
<div id="header">
SignalR Chat Room
</div>
<br />
<br />
<br />
<div id="divContainer">
<div id="divLogin" class="login">
<div>
Your Name:<br />
<input id="txtNickName" type="text" class="textBox" />
</div>
<div id="divButton">
<input id="btnStartChat" type="button" class="submitButton" value="Start Chat" />
</div>
</div>
<div id="divChat" class="chatRoom">
<div class="title">
Welcome to Chat Room [<span id='spanUser'></span>]
</div>
<div class="content">
<div id="divChatWindow" class="chatWindow">
</div>
<div id="divusers" class="users">
</div>
</div>
<div class="messageBar">
<input class="textbox" type="text" id="txtMessage" />
<input id="btnSendMsg" type="button" value="Send" class="submitButton" />
</div>
</div>
<input id="hdId" type="hidden" />
<input id="hdUserName" type="hidden" />
</div>
</body>
</html>
You are referring to the client object of an undefined object. So I have been searching inside your code for
.client
These were the results:
chatHub.client.onConnected
chatHub.client.onNewUserConnected
chatHub.client.onUserDisconnected
chatHub.client.messageReceived
chatHub.client.sendPrivateMessage
So, if you look at the results, it becomes obvious that chatHub is undefined somewhere. This is how you initialize it:
var chatHub = $.connection.chatHub;
I wonder what is inside $.connection. Are you missing a script from your html?
A couple of things...
You're using an old signalr version, have you tried upgrading to the latest?
Otherwise; I had a similar problem, I had to solve it by setting up the connection without the generated proxy (/signalr/hubs).
See this link http://www.asp.net/signalr/overview/guide-to-the-api/hubs-api-guide-javascript-client and instead of setting it as a "generated proxy", implement it without it. (Search for "Without the generated proxy")

Categories

Resources