Implementing chat rooms via WebSockets - javascript

I am trying to implement a chat for my web site using web sockets.Gobal chatting works fine. But i don't know how to make separate chat rooms. I've made and array to store separate connections but. When each time i open a new connection and added to the array the messages are send global to all opened sockets.
Adding js code here.
var sockets = []; //array that stores connections
function addText(e) {
console.log(activeChatWindow + " " + e);
if (isMyMsg(e)) {
$("#" + activeChatWindow).append($("<p class=\"Msg\" ></p>").text(e));
} else {
$("#" + activeChatWindow).append(
$("<p class=\"Msg\" id=\"recvMsg\"></p>").text(e));
}
$("#userInput").val("");
}
function sendText(user) {
var msg = formatText();
msg += $("#userInput").val();
console.log(sockets[user]);
sockets[user].send(msg);
}
function formatText() {
var date = new Date();
var text = u;
text += "[" + date.getDate() + "." + (date.getMonth() + 1) + "." + date.getFullYear() + ":" + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds() + "]: ";
return text;
}
function isMyMsg(e) {
var i = e.indexOf("[");
var user = e.slice(0, i);
if (user == u)
return true;
return false;
}
function openNewConnection(user) {
sockets[user] = new WebSocket("ws://localhost:8080/socket");
console.log(sockets[user]);
sockets[user].onopen = function(event) {
console.log('Connection open!');
};
sockets[user].onmessage = function(event) {
console.log(event.data + " " + user);
addText(event.data);
};
}
$(window).load(
function() {
for (var friend in myFriends) {
loadFriend(myFriends[friend], friend);
console.log("hello");
};
$("#send").click(function(e) {
sendText(activeChatWindow);
});
$("#userInput").keypress(function(e) {
if (e.which == 13) {
e.preventDefault();
sendText(activeChatWindow);
}
});
});

Related

How can I use the Eclipse Paho JavaScript Client to connect to test.mosquitto.org?

I am new to the IOT world and have been confused why I have not been able to use the Eclipse Paho JavaScript Client to connect to test.mosquitto.org.
I have used Port: 8080 and Path: /mqtt as has been suggested in other paho-mqtt questions, but am met with a Failed to connect: AMQJS0007E Socket error:undefined when using this Eclipse web client.
I have used the HiveMQ WebClient and have been able to connect, publish and subscribe to both test.mosquitto.org (Port 8080) and iot.eclipse.org (Port 443).
I have noticed that HiveMQ sources mqttws31.js compared to Paho Eclipse's paho-mqtt.js, but am unsure of the significance.
I would say there are two parts to this question:
What am I missing to get the Eclipse Paho JavaScript Client to connect to test.mosquitto.org ?
What is the difference between mqttws31.js and paho-mqtt.js that allows one to connect to test.mosquitto.org relatively painlessly compared to the other?
Thanks !
Relevant Code:
The code below is taken directly from the page source of https://www.eclipse.org/paho/clients/js/utility/
paho-mqtt.js: https://www.eclipse.org/paho/js/paho-mqtt.js
utility.js (handles button callbacks):
/*******************************************************************************
* Copyright (c) 2015 IBM Corp.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* James Sutton - Initial Contribution
*******************************************************************************/
/*
Eclipse Paho MQTT-JS Utility
This utility can be used to test the Eclipse Paho MQTT Javascript client.
*/
// Create a client instance
var client = null;
var connected = false;
logMessage("INFO", "Starting Eclipse Paho JavaScript Utility.");
// Things to do as soon as the page loads
document.getElementById("clientIdInput").value = "js-utility-" + makeid();
// called when the client connects
function onConnect(context) {
// Once a connection has been made, make a subscription and send a message.
var connectionString = context.invocationContext.host + ":" + context.invocationContext.port + context.invocationContext.path;
logMessage("INFO", "Connection Success ", "[URI: ", connectionString, ", ID: ", context.invocationContext.clientId, "]");
var statusSpan = document.getElementById("connectionStatus");
statusSpan.innerHTML = "Connected to: " + connectionString + " as " + context.invocationContext.clientId;
connected = true;
setFormEnabledState(true);
}
function onConnected(reconnect, uri) {
// Once a connection has been made, make a subscription and send a message.
logMessage("INFO", "Client Has now connected: [Reconnected: ", reconnect, ", URI: ", uri, "]");
connected = true;
}
function onFail(context) {
logMessage("ERROR", "Failed to connect. [Error Message: ", context.errorMessage, "]");
var statusSpan = document.getElementById("connectionStatus");
statusSpan.innerHTML = "Failed to connect: " + context.errorMessage;
connected = false;
setFormEnabledState(false);
}
// called when the client loses its connection
function onConnectionLost(responseObject) {
if (responseObject.errorCode !== 0) {
logMessage("INFO", "Connection Lost. [Error Message: ", responseObject.errorMessage, "]");
}
connected = false;
}
// called when a message arrives
function onMessageArrived(message) {
logMessage("INFO", "Message Recieved: [Topic: ", message.destinationName, ", Payload: ", message.payloadString, ", QoS: ", message.qos, ", Retained: ", message.retained, ", Duplicate: ", message.duplicate, "]");
var messageTime = new Date().toISOString();
// Insert into History Table
var table = document.getElementById("incomingMessageTable").getElementsByTagName("tbody")[0];
var row = table.insertRow(0);
row.insertCell(0).innerHTML = message.destinationName;
row.insertCell(1).innerHTML = safeTagsRegex(message.payloadString);
row.insertCell(2).innerHTML = messageTime;
row.insertCell(3).innerHTML = message.qos;
if (!document.getElementById(message.destinationName)) {
var lastMessageTable = document.getElementById("lastMessageTable").getElementsByTagName("tbody")[0];
var newlastMessageRow = lastMessageTable.insertRow(0);
newlastMessageRow.id = message.destinationName;
newlastMessageRow.insertCell(0).innerHTML = message.destinationName;
newlastMessageRow.insertCell(1).innerHTML = safeTagsRegex(message.payloadString);
newlastMessageRow.insertCell(2).innerHTML = messageTime;
newlastMessageRow.insertCell(3).innerHTML = message.qos;
} else {
// Update Last Message Table
var lastMessageRow = document.getElementById(message.destinationName);
lastMessageRow.id = message.destinationName;
lastMessageRow.cells[0].innerHTML = message.destinationName;
lastMessageRow.cells[1].innerHTML = safeTagsRegex(message.payloadString);
lastMessageRow.cells[2].innerHTML = messageTime;
lastMessageRow.cells[3].innerHTML = message.qos;
}
}
function connectionToggle() {
if (connected) {
disconnect();
} else {
connect();
}
}
function connect() {
var hostname = document.getElementById("hostInput").value;
var port = document.getElementById("portInput").value;
var clientId = document.getElementById("clientIdInput").value;
var path = document.getElementById("pathInput").value;
var user = document.getElementById("userInput").value;
var pass = document.getElementById("passInput").value;
var keepAlive = Number(document.getElementById("keepAliveInput").value);
var timeout = Number(document.getElementById("timeoutInput").value);
var tls = document.getElementById("tlsInput").checked;
var automaticReconnect = document.getElementById("automaticReconnectInput").checked;
var cleanSession = document.getElementById("cleanSessionInput").checked;
var lastWillTopic = document.getElementById("lwtInput").value;
var lastWillQos = Number(document.getElementById("lwQosInput").value);
var lastWillRetain = document.getElementById("lwRetainInput").checked;
var lastWillMessageVal = document.getElementById("lwMInput").value;
if (path.length > 0) {
client = new Paho.Client(hostname, Number(port), path, clientId);
} else {
client = new Paho.Client(hostname, Number(port), clientId);
}
logMessage("INFO", "Connecting to Server: [Host: ", hostname, ", Port: ", port, ", Path: ", client.path, ", ID: ", clientId, "]");
// set callback handlers
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
client.onConnected = onConnected;
var options = {
invocationContext: { host: hostname, port: port, path: client.path, clientId: clientId },
timeout: timeout,
keepAliveInterval: keepAlive,
cleanSession: cleanSession,
useSSL: tls,
reconnect: automaticReconnect,
onSuccess: onConnect,
onFailure: onFail
};
if (user.length > 0) {
options.userName = user;
}
if (pass.length > 0) {
options.password = pass;
}
if (lastWillTopic.length > 0) {
var lastWillMessage = new Paho.Message(lastWillMessageVal);
lastWillMessage.destinationName = lastWillTopic;
lastWillMessage.qos = lastWillQos;
lastWillMessage.retained = lastWillRetain;
options.willMessage = lastWillMessage;
}
// connect the client
client.connect(options);
var statusSpan = document.getElementById("connectionStatus");
statusSpan.innerHTML = "Connecting...";
}
function disconnect() {
logMessage("INFO", "Disconnecting from Server.");
client.disconnect();
var statusSpan = document.getElementById("connectionStatus");
statusSpan.innerHTML = "Connection - Disconnected.";
connected = false;
setFormEnabledState(false);
}
// Sets various form controls to either enabled or disabled
function setFormEnabledState(enabled) {
// Connection Panel Elements
if (enabled) {
document.getElementById("clientConnectButton").innerHTML = "Disconnect";
} else {
document.getElementById("clientConnectButton").innerHTML = "Connect";
}
document.getElementById("hostInput").disabled = enabled;
document.getElementById("portInput").disabled = enabled;
document.getElementById("clientIdInput").disabled = enabled;
document.getElementById("pathInput").disabled = enabled;
document.getElementById("userInput").disabled = enabled;
document.getElementById("passInput").disabled = enabled;
document.getElementById("keepAliveInput").disabled = enabled;
document.getElementById("timeoutInput").disabled = enabled;
document.getElementById("tlsInput").disabled = enabled;
document.getElementById("automaticReconnectInput").disabled = enabled;
document.getElementById("cleanSessionInput").disabled = enabled;
document.getElementById("lwtInput").disabled = enabled;
document.getElementById("lwQosInput").disabled = enabled;
document.getElementById("lwRetainInput").disabled = enabled;
document.getElementById("lwMInput").disabled = enabled;
// Publish Panel Elements
document.getElementById("publishTopicInput").disabled = !enabled;
document.getElementById("publishQosInput").disabled = !enabled;
document.getElementById("publishMessageInput").disabled = !enabled;
document.getElementById("publishButton").disabled = !enabled;
document.getElementById("publishRetainInput").disabled = !enabled;
// Subscription Panel Elements
document.getElementById("subscribeTopicInput").disabled = !enabled;
document.getElementById("subscribeQosInput").disabled = !enabled;
document.getElementById("subscribeButton").disabled = !enabled;
document.getElementById("unsubscribeButton").disabled = !enabled;
}
function publish() {
var topic = document.getElementById("publishTopicInput").value;
var qos = document.getElementById("publishQosInput").value;
var message = document.getElementById("publishMessageInput").value;
var retain = document.getElementById("publishRetainInput").checked;
logMessage("INFO", "Publishing Message: [Topic: ", topic, ", Payload: ", message, ", QoS: ", qos, ", Retain: ", retain, "]");
message = new Paho.Message(message);
message.destinationName = topic;
message.qos = Number(qos);
message.retained = retain;
client.send(message);
}
function subscribe() {
var topic = document.getElementById("subscribeTopicInput").value;
var qos = document.getElementById("subscribeQosInput").value;
logMessage("INFO", "Subscribing to: [Topic: ", topic, ", QoS: ", qos, "]");
client.subscribe(topic, { qos: Number(qos) });
}
function unsubscribe() {
var topic = document.getElementById("subscribeTopicInput").value;
logMessage("INFO", "Unsubscribing: [Topic: ", topic, "]");
client.unsubscribe(topic, {
onSuccess: unsubscribeSuccess,
onFailure: unsubscribeFailure,
invocationContext: { topic: topic }
});
}
function unsubscribeSuccess(context) {
logMessage("INFO", "Unsubscribed. [Topic: ", context.invocationContext.topic, "]");
}
function unsubscribeFailure(context) {
logMessage("ERROR", "Failed to unsubscribe. [Topic: ", context.invocationContext.topic, ", Error: ", context.errorMessage, "]");
}
function clearHistory() {
var table = document.getElementById("incomingMessageTable");
//or use : var table = document.all.tableid;
for (var i = table.rows.length - 1; i > 0; i--) {
table.deleteRow(i);
}
}
// Just in case someone sends html
function safeTagsRegex(str) {
return str.replace(/&/g, "&").replace(/</g, "<").
replace(/>/g, ">");
}
function makeid() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 5; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
function logMessage(type, ...content) {
var consolePre = document.getElementById("consolePre");
var date = new Date();
var timeString = date.toUTCString();
var logMessage = timeString + " - " + type + " - " + content.join("");
consolePre.innerHTML += logMessage + "\n";
if (type === "INFO") {
console.info(logMessage);
} else if (type === "ERROR") {
console.error(logMessage);
} else {
console.log(logMessage);
}
}
The code below is taken directly from the page source of http://www.hivemq.com/demos/websocket-client/
mqttws31.js: http://www.hivemq.com/demos/websocket-client/js/mqttws31.js
app.js (handles app callbacks):
/**
* Copyright 2013 dc-square GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* #author: Christoph Schäbel
*/
var websocketclient = {
'client': null,
'lastMessageId': 1,
'lastSubId': 1,
'subscriptions': [],
'messages': [],
'connected': false,
'connect': function () {
var host = $('#urlInput').val();
var port = parseInt($('#portInput').val(), 10);
var clientId = $('#clientIdInput').val();
var username = $('#userInput').val();
var password = $('#pwInput').val();
var keepAlive = parseInt($('#keepAliveInput').val());
var cleanSession = $('#cleanSessionInput').is(':checked');
var lwTopic = $('#lwTopicInput').val();
var lwQos = parseInt($('#lwQosInput').val());
var lwRetain = $('#LWRInput').is(':checked');
var lwMessage = $('#LWMInput').val();
var ssl = $('#sslInput').is(':checked');
this.client = new Messaging.Client(host, port, clientId);
this.client.onConnectionLost = this.onConnectionLost;
this.client.onMessageArrived = this.onMessageArrived;
var options = {
timeout: 3,
keepAliveInterval: keepAlive,
cleanSession: cleanSession,
useSSL: ssl,
onSuccess: this.onConnect,
onFailure: this.onFail
};
if (username.length > 0) {
options.userName = username;
}
if (password.length > 0) {
options.password = password;
}
if (lwTopic.length > 0) {
var willmsg = new Messaging.Message(lwMessage);
willmsg.qos = lwQos;
willmsg.destinationName = lwTopic;
willmsg.retained = lwRetain;
options.willMessage = willmsg;
}
this.client.connect(options);
},
'onConnect': function () {
websocketclient.connected = true;
console.log("connected");
var body = $('body').addClass('connected').removeClass('notconnected').removeClass('connectionbroke');
websocketclient.render.hide('conni');
websocketclient.render.show('publish');
websocketclient.render.show('sub');
websocketclient.render.show('messages');
},
'onFail': function (message) {
websocketclient.connected = false;
console.log("error: " + message.errorMessage);
websocketclient.render.showError('Connect failed: ' + message.errorMessage);
},
'onConnectionLost': function (responseObject) {
websocketclient.connected = false;
if (responseObject.errorCode !== 0) {
console.log("onConnectionLost:" + responseObject.errorMessage);
}
$('body.connected').removeClass('connected').addClass('notconnected').addClass('connectionbroke');
websocketclient.render.show('conni');
websocketclient.render.hide('publish');
websocketclient.render.hide('sub');
websocketclient.render.hide('messages');
//Cleanup messages
websocketclient.messages = [];
websocketclient.render.clearMessages();
//Cleanup subscriptions
websocketclient.subscriptions = [];
websocketclient.render.clearSubscriptions();
},
'onMessageArrived': function (message) {
// console.log("onMessageArrived:" + message.payloadString + " qos: " + message.qos);
var subscription = websocketclient.getSubscriptionForTopic(message.destinationName);
var messageObj = {
'topic': message.destinationName,
'retained': message.retained,
'qos': message.qos,
'payload': message.payloadString,
'timestamp': moment(),
'subscriptionId': subscription.id,
'color': websocketclient.getColorForSubscription(subscription.id)
};
console.log(messageObj);
messageObj.id = websocketclient.render.message(messageObj);
websocketclient.messages.push(messageObj);
},
'disconnect': function () {
this.client.disconnect();
},
'publish': function (topic, payload, qos, retain) {
if (!websocketclient.connected) {
websocketclient.render.showError("Not connected");
return false;
}
var message = new Messaging.Message(payload);
message.destinationName = topic;
message.qos = qos;
message.retained = retain;
this.client.send(message);
},
'subscribe': function (topic, qosNr, color) {
if (!websocketclient.connected) {
websocketclient.render.showError("Not connected");
return false;
}
if (topic.length < 1) {
websocketclient.render.showError("Topic cannot be empty");
return false;
}
if (_.find(this.subscriptions, { 'topic': topic })) {
websocketclient.render.showError('You are already subscribed to this topic');
return false;
}
this.client.subscribe(topic, {qos: qosNr});
if (color.length < 1) {
color = '999999';
}
var subscription = {'topic': topic, 'qos': qosNr, 'color': color};
subscription.id = websocketclient.render.subscription(subscription);
this.subscriptions.push(subscription);
return true;
},
'unsubscribe': function (id) {
var subs = _.find(websocketclient.subscriptions, {'id': id});
this.client.unsubscribe(subs.topic);
websocketclient.subscriptions = _.filter(websocketclient.subscriptions, function (item) {
return item.id != id;
});
websocketclient.render.removeSubscriptionsMessages(id);
},
'deleteSubscription': function (id) {
var elem = $("#sub" + id);
if (confirm('Are you sure ?')) {
elem.remove();
this.unsubscribe(id);
}
},
'getRandomColor': function () {
var r = (Math.round(Math.random() * 255)).toString(16);
var g = (Math.round(Math.random() * 255)).toString(16);
var b = (Math.round(Math.random() * 255)).toString(16);
return r + g + b;
},
'getSubscriptionForTopic': function (topic) {
var i;
for (i = 0; i < this.subscriptions.length; i++) {
if (this.compareTopics(topic, this.subscriptions[i].topic)) {
return this.subscriptions[i];
}
}
return false;
},
'getColorForPublishTopic': function (topic) {
var id = this.getSubscriptionForTopic(topic);
return this.getColorForSubscription(id);
},
'getColorForSubscription': function (id) {
try {
if (!id) {
return '99999';
}
var sub = _.find(this.subscriptions, { 'id': id });
if (!sub) {
return '999999';
} else {
return sub.color;
}
} catch (e) {
return '999999';
}
},
'compareTopics': function (topic, subTopic) {
var pattern = subTopic.replace("+", "(.*?)").replace("#", "(.*)");
var regex = new RegExp("^" + pattern + "$");
return regex.test(topic);
},
'render': {
'showError': function (message) {
alert(message);
},
'messages': function () {
websocketclient.render.clearMessages();
_.forEach(websocketclient.messages, function (message) {
message.id = websocketclient.render.message(message);
});
},
'message': function (message) {
var largest = websocketclient.lastMessageId++;
var html = '<li class="messLine id="' + largest + '">' +
' <div class="row large-12 mess' + largest + '" style="border-left: solid 10px #' + message.color + '; ">' +
' <div class="large-12 columns messageText">' +
' <div class="large-3 columns date">' + message.timestamp.format("YYYY-MM-DD HH:mm:ss") + '</div>' +
' <div class="large-5 columns topicM truncate" id="topicM' + largest + '" title="' + Encoder.htmlEncode(message.topic, 0) + '">Topic: ' + Encoder.htmlEncode(message.topic) + '</div>' +
' <div class="large-2 columns qos">Qos: ' + message.qos + '</div>' +
' <div class="large-2 columns retain">';
if (message.retained) {
html += 'Retained';
}
html += ' </div>' +
' <div class="large-12 columns message break-words">' + Encoder.htmlEncode(message.payload) + '</div>' +
' </div>' +
' </div>' +
'</li>';
$("#messEdit").prepend(html);
return largest;
},
'subscriptions': function () {
websocketclient.render.clearSubscriptions();
_.forEach(websocketclient.subscriptions, function (subs) {
subs.id = websocketclient.render.subscription(subs);
});
},
'subscription': function (subscription) {
var largest = websocketclient.lastSubId++;
$("#innerEdit").append(
'<li class="subLine" id="sub' + largest + '">' +
' <div class="row large-12 subs' + largest + '" style="border-left: solid 10px #' + subscription.color + '; background-color: #ffffff">' +
' <div class="large-12 columns subText">' +
' <div class="large-1 columns right closer">' +
' x' +
' </div>' +
' <div class="qos">Qos: ' + subscription.qos + '</div>' +
' <div class="topic truncate" id="topic' + largest + '" title="' + Encoder.htmlEncode(subscription.topic, 0) + '">' + Encoder.htmlEncode(subscription.topic) + '</div>' +
' </div>' +
' </div>' +
'</li>');
return largest;
},
'toggleAll': function () {
websocketclient.render.toggle('conni');
websocketclient.render.toggle('publish');
websocketclient.render.toggle('messages');
websocketclient.render.toggle('sub');
},
'toggle': function (name) {
$('.' + name + 'Arrow').toggleClass("closed");
$('.' + name + 'Top').toggleClass("closed");
var elem = $('#' + name + 'Main');
elem.slideToggle();
},
'hide': function (name) {
$('.' + name + 'Arrow').addClass("closed");
$('.' + name + 'Top').addClass("closed");
var elem = $('#' + name + 'Main');
elem.slideUp();
},
'show': function (name) {
$('.' + name + 'Arrow').removeClass("closed");
$('.' + name + 'Top').removeClass("closed");
var elem = $('#' + name + 'Main');
elem.slideDown();
},
'removeSubscriptionsMessages': function (id) {
websocketclient.messages = _.filter(websocketclient.messages, function (item) {
return item.subscriptionId != id;
});
websocketclient.render.messages();
},
'clearMessages': function () {
$("#messEdit").empty();
},
'clearSubscriptions': function () {
$("#innerEdit").empty();
}
}
};
I think I am a bit late...but I leave here for posterity.
The Paho JS library has undergo a series of changes before release 1.0.3 and the last one 1.1.0.
If you refer to a mqttws31.js probably you was using a version earlier than 1.0.3, because from 1.0.3 the main js file was renamed to paho-mqtt.js.
Can be the reason why something in your code was working differently from HiveMQ version.
I tried to sum the situation here

Play a sequence of images with JS, using $timeout to schedule frames

I'm using AngularJS to prefetch images in cache client and then I want to animate those prefetched images.
My code for the prefetching:
$scope.prefetch=function(limit) {
for (var i=0; i<limit; i++) {
var date = new Date($scope.dt);
if ($scope.fileFlag == false) {
if ($scope.viewmodel.timeResolution == 'yearly')
date = new Date(date.setFullYear(date.getFullYear() + i));
else if ($scope.viewmodel.timeResolution == 'monthly')
date = new Date(date.setMonth(date.getMonth() + i));
else if ($scope.viewmodel.timeResolution == 'daily') {
date = new Date(date.setDate(date.getDate() + i));
}
} else {
date = $scope.files[$scope.files.indexOf($scope.idSelectedVote) + i];
}
console.log( $http.get(site_url + "mwf/" + $scope.viewmodel.dataSet + "/" + $scope.viewmodel.varName + "/" + $scope.viewmodel.region + "/" + date + "/map/?vMin=" + $scope.VMin + "&vMax=" + $scope.VMax + "&type=" + $scope.viewmodel.type + "&cmap=" + $scope.viewmodel.colorMap, {'cache': true}));
}
};
then i do something like this to play those images
$scope.play=function(limit) {
for (var i=0; i<limit; i++) {
$scope.map.src= site_url + "mwf/" + $scope.viewmodel.dataSet + "/" + $scope.viewmodel.varName + "/" + $scope.viewmodel.region + "/" + parseInt(date)+i + "/map/?vMin=" + $scope.VMin + "&vMax=" + $scope.VMax + "&type=" + $scope.viewmodel.type + "&cmap=" + $scope.viewmodel.colorMap;
$scope.sleepFor(500);
}
};
$scope.sleepFor = function( sleepDuration ) {
var now = new Date().getTime();
while(new Date().getTime() < now + sleepDuration){ /* do nothing */ }
}
My problem is when I call play(4) it displays only the first and the last images and not an animation. Any idea on how can I improve this code or a different approach so I can do this?
Your sleepFor is an idle loop: you spin and do nothing, but you prevent any other work from being done. This is not the way in Javascript to delay work for a set period of time, or schedule a function to be run at a later time. In Javascript we use window.setTimeout -- and in Angular we have the convenient $timeout service to provide that:
$scope.play = function(limit) {
for (var i=0; i < limit; i++) {
$scope.map.src = site_url + "mwf/" + $scope.viewmodel.dataSet + "/" + $scope.viewmodel.varName + "/" + $scope.viewmodel.region + "/" + parseInt(date)+i + "/map/?vMin=" + $scope.VMin + "&vMax=" + $scope.VMax + "&type=" + $scope.viewmodel.type + "&cmap=" + $scope.viewmodel.colorMap;
var nextFrameMs = 500;
$timeout($scope.play, nextFrameMs);
}
};
In your example, wherever your $scope is provided to you -- assuming this is in a controller, you will have some line like module.controller($scope, ...) -- you will have to inject the $timeout service to be able to use it.
Additional resources:
Angular's documentation on $timeout
MDN documentation of window.setTimeout
You have to use intervals otherwise your code will block the execution of other code
Using Angular's built in $interval service is the solution:
var playInterval;
$scope.play = function(limit) {
var interval = 1000 / 20; //20 frames per second
var i = 0;
$interval.cancel(playInterval); //stop previous animations if any
if(i < limit) {
$scope.map.src = getSrc(i++);
var cache = $interval(function() {
if(i >= limit) {
return $interval.cancel(playInterval); //or you can replace with `i = 0;` to loop the animation
}
$scope.map.src = getSrc(i++);
}, interval);
}
};
function getSrc(i) {
return site_url + "mwf/" + $scope.viewmodel.dataSet + "/" + $scope.viewmodel.varName + "/" + $scope.viewmodel.region + "/" + parseInt(date)+i + "/map/?vMin=" + $scope.VMin + "&vMax=" + $scope.VMax + "&type=" + $scope.viewmodel.type + "&cmap=" + $scope.viewmodel.colorMap;
}

JavaScript not running on formLoad, CRM 2011 for outlook

I have recently added CRM 2011 for Outlook client to a new machine, I have a script which runs on the payment entity formLoad which calculates the remainingAmount left after taking into account all the payment allocations and deducting from the TotalAmount..
However, when I access the data through Outlook, the script seems to not be firing off on formLoad.. If i access the same data through the web portal then the script fires off without an issue - this leads me to think that there is a setting somewhere which you need to enable to allow custom javascript to run in Outlook for the CRM?
My script is below for the paymentLoad():
function PaymentOnLoad() {
setTimeout(attachEventToGrid, 2500);
if (crmForm.ObjectId != null) {
var PaymentAmount = Xrm.Page.getAttribute("new_accountpaymentamount").getValue();
var OSAmount = CalcOutstandingPaymentAmount(crmForm.ObjectId);
Xrm.Page.getAttribute("new_remainingamount").setValue(parseFloat(eval(rounddec(OSAmount))));
if ((PaymentAmount != null) && (OSAmount - PaymentAmount != 0)) {
Xrm.Page.ui.controls.get("new_paymentamount").setDisabled(true);
}
}
}
function rounddec(value) {
return Math.round(value * 100) / 100;
}
function attachEventToGrid() {
// Attach a refresh event to the PaymentAllocations grid
var targetgrid = document.getElementById("PaymentAllocations");
if (targetgrid) {
if (targetgrid.control.add_onRefresh != undefined) {
targetgrid.control.add_onRefresh(ReLoad);
}
else {
targetgrid.attachEvent("onrefresh", ReLoad);
}
}
else {
setTimeout(attachEventToGrid, 2500);
}
}
function PaymentAllocationOnLoad() {
OnPaymentTypeSelection();
if (Xrm.Page.getAttribute("new_payment").getValue()[0] != null) {
var OSPaymentAmount = CalcOutstandingPaymentAmount(Xrm.Page.getAttribute("new_payment").getValue()[0].id);
Xrm.Page.getAttribute("new_paymentremainingamount").setValue(parseFloat(eval(OSPaymentAmount)));
if (Xrm.Page.getAttribute("new_invoice").getValue() != null) {
var OSInvoiceAmount = CalcOutstandingInvoiceAmount(Xrm.Page.getAttribute("new_invoice").getValue()[0].id);
Xrm.Page.getAttribute("new_invoiceremainingamount").setValue(parseFloat(eval(OSInvoiceAmount)));
Xrm.Page.ui.controls.get("new_paymentamount").setDisabled(true);
}
}
}
function CalcOutstandingPaymentAmount(paymentid) {
_oService = new FetchUtil(_sOrgName, _sServerUrl);
var sFetchPayment = "<fetch mapping='logical'>" +
"<entity name='new_payment'>" +
"<attribute name='new_paymentamount' />" +
"<attribute name='new_accountpaymentamount' />" +
"<filter type='and'>" +
"<condition attribute = 'new_paymentid' operator='eq' value='" + paymentid + "'/>" +
"</filter>" +
"</entity>" +
"</fetch>";
var fetchResultPayment = _oService.Fetch(sFetchPayment, null);
var sFetch = "<fetch mapping='logical'>" +
"<entity name='new_paymentinvoiceallocation'>" +
"<attribute name='new_allocatedamount' />" +
"<filter type='and'>" +
"<condition attribute = 'new_payment' operator='eq' value='" + paymentid + "'/>" +
"</filter>" +
"</entity>" +
"</fetch>";
var fetchApplication = _oService.Fetch(sFetch, null);
var TotalAmount = 0;
if (fetchResultPayment != null) {
TotalAmount = fetchResultPayment.results[0].attributes.new_accountpaymentamount.value;
}
if ((fetchResultPayment != null) && (fetchApplication != null)) {
for (var i = 0;
i < fetchApplication.results.length;
i++) {
TotalAmount -= fetchApplication.results[i].attributes.new_allocatedamount.value;
}
}
return TotalAmount;
}
Any suggestions would be appreciated.

CRM Javascript, multiple independent sets of script on the same OnLoad form

I am new to Javascript, I basically have a form to edit on CRM. I have two pieces of script, independent of each other, they both work fine on their own when I use the OnLoad feature, however when I put both sets of code into the same script developer (since its for the same form on CRM), one of them does not work.
Can anyone help and is there any special syntax to have multiple scripts on the same form?
Thanks
The Javascript is below:
var _roles = 'Compliance'; //array of security roles name
var _fields = 'new_pend'; // array of field schema names to enable
UpdateFields();
/* Functions */
function UpdateFields() {
var oXml = GetCurrentUserRoles();
if (oXml != null) {
var roles = oXml.selectNodes("//BusinessEntity/q1:name");
if (roles != null) {
for (i = 0; i < roles.length; i++) {
for (j = 0; j < _roles.length; j++) {
if (roles[i].text == _roles[j]) {
for (k = 0; k < _fields.length; k++) {
try {
document.getElementById(_fields[k]).Disabled = false;
} catch (e) {
}
}
return;
}
}
}
}
}
return;
}
function GetCurrentUserRoles() {
var xml = "" +
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
GenerateAuthenticationHeader() +
" <soap:Body>" +
" <RetrieveMultiple xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
" <query xmlns:q1=\"http://schemas.microsoft.com/crm/2006/Query\" xsi:type=\"q1:QueryExpression\">" +
" <q1:EntityName>role</q1:EntityName>" +
" <q1:ColumnSet xsi:type=\"q1:ColumnSet\">" +
" <q1:Attributes>" +
" <q1:Attribute>name</q1:Attribute>" +
" </q1:Attributes>" +
" </q1:ColumnSet>" +
" <q1:Distinct>false</q1:Distinct>" +
" <q1:LinkEntities>" +
" <q1:LinkEntity>" +
" <q1:LinkFromAttributeName>roleid</q1:LinkFromAttributeName>" +
" <q1:LinkFromEntityName>role</q1:LinkFromEntityName>" +
" <q1:LinkToEntityName>systemuserroles</q1:LinkToEntityName>" +
" <q1:LinkToAttributeName>roleid</q1:LinkToAttributeName>" +
" <q1:JoinOperator>Inner</q1:JoinOperator>" +
" <q1:LinkEntities>" +
" <q1:LinkEntity>" +
" <q1:LinkFromAttributeName>systemuserid</q1:LinkFromAttributeName>" +
" <q1:LinkFromEntityName>systemuserroles</q1:LinkFromEntityName>" +
" <q1:LinkToEntityName>systemuser</q1:LinkToEntityName>" +
" <q1:LinkToAttributeName>systemuserid</q1:LinkToAttributeName>" +
" <q1:JoinOperator>Inner</q1:JoinOperator>" +
" <q1:LinkCriteria>" +
" <q1:FilterOperator>And</q1:FilterOperator>" +
" <q1:Conditions>" +
" <q1:Condition>" +
" <q1:AttributeName>systemuserid</q1:AttributeName>" +
" <q1:Operator>EqualUserId</q1:Operator>" +
" </q1:Condition>" +
" </q1:Conditions>" +
" </q1:LinkCriteria>" +
" </q1:LinkEntity>" +
" </q1:LinkEntities>" +
" </q1:LinkEntity>" +
" </q1:LinkEntities>" +
" </query>" +
" </RetrieveMultiple>" +
" </soap:Body>" +
"</soap:Envelope>" +
"";
var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
xmlHttpRequest.setRequestHeader("SOAPAction", " http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple");
xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
xmlHttpRequest.send(xml);
var resultXml = xmlHttpRequest.responseXML;
return (resultXml);
}
Hi everyone who has read this, I found a solution to the problem.
I used an If statement to define what the output should be based on an input into the function. This is shown in the code below, Use this code with the function GetCurrentUserRoles. Thanks for all the help.
if(UserHasRole("Collections") ==true)
{
crmForm.all.new_pend.Disabled = false;
return;
}
else if (UserHasRole("Collections") ==false)
{
crmForm.all.new_pend.Disabled = true;
return;
}
function UserHasRole(roleName)
{
//get Current User Roles, oXml is an object
var oXml = GetCurrentUserRoles();
if(oXml != null)
{
//select the node text
var roles = oXml.selectNodes("//BusinessEntity/q1:name");
if(roles != null)
{
for( i = 0; i < roles.length; i++)
{
if(roles[i].text == roleName)
{
//return true if user has this role
return true;
}
}
}
}
//otherwise return false
return false;
}

HTML read javascript and put result into a div

I'm new to HTML/javascript and I want to make something that displays Last.FM current playing songs, into a div on html, which displays it in text, I have a code that sends the current song through a chat on www.irccloud.com, and I was wondering If you could change it so that It could get received and put into a DIV on a page, the code is below:
and var r is the completed code, so how would I do something in the div that picks up the source as the link above and then grabs var r from it? If so, how would I do it??
I have tried the following code here
Sorry if I do not make sense.
(function () {
var e = "DeviousRunner";
window.lfmRecentTrack = function (t) {
var n = (new Array).concat(t.recenttracks.track)[0];
var album, spurl;
if (n.album["#text"]) {
album = " (from " + n.album["#text"] + ")";
} else {
album = "";
}
try {
var spotify = new XMLHttpRequest();
spotify.open("GET", "https://ws.spotify.com/search/1/track.json?q=" + encodeURIComponent(n.artist["#text"] + " - " + n.name), false);
spotify.send();
var spotresp = JSON.parse(spotify.responseText);
if (spotresp["tracks"].length > 0) {
//var urisplit = spotresp["tracks"][0]["href"].split(":");
//spurl = " https://open.spotify.com/" + urisplit[1] + "/" + urisplit[2];
spurl = spotresp["tracks"][0]["href"];
} else {
console.log("spotify: couldn't get url");
spurl = "";
}
} catch(e) {
console.log("spotify: " + e.message);
spurl = "";
}
var r = "is listening to " + n.name + " by " + n.artist["#text"] + " " + album + " (" + spurl + ")";
}
var n = document.createElement("script");
n.setAttribute("type", "text/javascript");
n.setAttribute("src", "https://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=" + e + "&api_key=dd5fb083b94a7196cf696b9d7d11bc63&limit=1&format=json&callback=window.lfmRecentTrack");
document.body.appendChild(n)
})();
I updated your FIDDLE,
by moving this:
var element = document.getElementById("rss");
element.innerHTML = r;
inside the function...
hope this is useful for you

Categories

Resources