i'm developping a chat application using gos socketBundle i'm trying to show connected users using this code in javascript .
when the subscribe is done to the channel connected users always connectedUsers are null?? could any one help me please ?
{{ ws_client()}}
<script type="text/javascript">
var websocket = WS.connect("ws://127.0.0.1:8080");
//var websocket = WS.connect("ws://{#{{ wsUrl }}#})");
websocket.on("socket/connect", function (session) {
session.subscribe("connected-users/channel", function (uri, payload) {
console.log(session);
console.log(payload);
var connectedUsers = JSON.parse(payload.connectedUsers);
var newtml = '';
connectedUsers.forEach(function (user) {
newtml += '<a name="toggle" class="connectedUserLink" onclick="talkToUser(\'' + user.id + '\', \'' + user.username + '\')">' + user.username + '</a>';
});
$('#connectedUserNbr').html(connectedUsers.length);
$('#connectedUserList').html(newtml);
});
});
websocket.on("socket/disconnect", function (error) {
//error provides us with some insight into the disconnection: error.reason and error.code
console.log("Disconnected for " + error.reason + " with code " + error.code);
});
</script>
Related
I don't know why my code is giving error while making the ajax call and not responding or working at all. I ran this on an html file. I took this function - getParameterByName() from another stackoverflow answer.tweet-container tag is down the code below outside this script and an empty division.I tried some jquery also.
<script>
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
$(document).ready(function(){
console.log("working");
var query = getParameterByName("q")
// console.log("query");
var tweetList = [];
function parseTweets(){
if (tweetList == 0){
$("#tweet-container").text("No tweets currently found.")
} else {
//tweets are existing, so parse and display them
$.each(parseTweets, function(key, value){
//console.log(key)
// console.log(value.user)
// console.log(value.content)
var tweetKey = value.key;
var tweetUser = value.user;
var tweetContent = value.content;
$("#tweet-container").append(
"<div class=\"media\"><div class=\"media-body\">" + tweetContent + "</br> via " + tweetUser.username + " | " + View + "</div></div><hr/>"
)
})
}
}
$.ajax({
url:"/api/tweet/",
data:{
"q": query
},
method: "GET",
success:function(data){
//console.log(data)
tweetList = data
parseTweets()
},
error:
function(data){
console.log("error")
console.log(data)
}
})
});
</script>
strong text
Fix the quotes to resolve your syntax error:
$("#tweet-container").append("<div class=\"media\"><div class=\"media-body\">" + tweetContent + " </br> via " + tweetUser.username + " | " + "View</div></div><hr/>")
I am learning AWS and as part of that I am trying to create a Lambda using node.js.
I am trying to invoke a webpage using the following, please correct me. What I am missing?
const opn = require('opn');
opn('http://google.com', {app: 'firefox'});
I wrote up a post detailing how to set this up if you only want to hit URLs with Lambda. You can find it here.
If you already know how to setup IAM permissions and scheduling with CloudWatch, the code I used accomplished this with Node.js 6.10 runtime:
exports.handler = (event, context, callback) => {
var urls = event.urls;
var http = require("http");
var https = require("https");
for (var i = 0; i < urls.length; i++) {
var protocol = urls[i].Protocol;
var domain = urls[i].Domain;
var queryString = urls[i].QueryString;
var url = protocol + "://" + domain + queryString;
if (protocol.toLowerCase() === "http") {
var j = i;
http.get(url, function(res) {
// Get around async.
var requestUrl = urls[j].Protocol + "://" + urls[j].Domain + urls[j].QueryString;
console.log("Response from " + requestUrl + ": ");
console.log(res.statusCode);
console.log(res.statusMessage);
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
} else if (protocol.toLowerCase() === "https") {
https.get(url, function(res) {
var j = i;
// Get around async.
var requestUrl = urls[j].Protocol + "://" + urls[j].Domain + urls[j].QueryString;
console.log("Response from " + requestUrl + ": ");
console.log(res.statusCode);
console.log(res.statusMessage);
}).on('error', function(e) {
console.log("Encountered error: " + e.message);
});
}
// Force break due to async -> output.
if ((i+1) == urls.length) {
break;
}
}
};
You would define the URLs you would like to invoke by passing an event object that is similar to the following:
{"urls": [{
"Protocol": "HTTP",
"Domain": "www.aaronmedacco.com",
"QueryString": ""}, {
"Protocol": "HTTPS",
"Domain": "www.google.com",
"QueryString": "?key=value"}]}
Again, if you want a step by step, check out this post. Simple to set up.
I have a aftersave on Parse cloud code. I have made changes to the table once but the aftersave hook triggers twice
1st Update (Actual update)
Input: {"object":{"addedBy":"tt","albumTitle":"ggh","approved":true,
"createdAt":"2015-12-14T03:07:27.253Z","image":
{"__type":"File","name":"tfss-e26ec608-5a0b-46a2-91db-33590139c4b3-
newImage.jpg","url":"http://files.parsetfss.com/0accbdba-e3f2-493d-
ac70-1c6bccc367b9/tfss-e26ec608-5a0b-46a2-91db-33590139c4b3-
newImage.jpg"},"objectId":"p4pLO70gQY","updatedAt":"2015-12-
14T03:07:37.733Z"}}
2nd Update (Shouldn't happen)
Input: {"object":{"addedBy":"tt","albumTitle":"ggh","approved":true,
"createdAt":"2015-12-14T03:07:27.253Z","image":
{"__type":"File","name":"tfss-e26ec608-5a0b-46a2-91db-33590139c4b3-
newImage.jpg","url":"http://files.parsetfss.com/0accbdba-e3f2-493d-
ac70-1c6bccc367b9/tfss-e26ec608-5a0b-46a2-91db-33590139c4b3-
newImage.jpg"},"objectId":"p4pLO70gQY","updatedAt":"2015-12-
14T03:07:38.038Z"}}
The only difference between the two updates is the updatedAt time. Will aftersave be triggered even if the update time changes?
How can I avoid the second aftersave execution?
Here is my cloud code :
Parse.Cloud.afterSave("Photos", function (request) {
var albumNameA = "";
var publicUser = "";
var albumOwner = "";
var photoUniqueId = "";
var isApproved = "";
albumNameA = request.object.get("albumTitle");
publicUser = request.object.get("addedBy");
photoUniqueId = request.object.id;
isApproved = request.object.get("approved");
if (request.object.get("createdAt").getTime() == request.object.get("updatedAt").getTime()) {
var getAlbumOwner = new Parse.Object.extend("Albums");
var q3 = new Parse.Query(getAlbumOwner);
q3.equalTo("title", albumNameA);
q3.first({
success: function (results) {
console.log("Checking for Creator name " + results.get("creatorName"));
albumOwner = results.get("creatorName");
console.log("Uploading a Photo Final " + albumNameA + "-by-" + publicUser + "--ownedby--" + albumOwner);
console.log("Uploading a Photo" + albumNameA + "-by-" + publicUser + "--" + photoUniqueId + "--" + isApproved);
var install = new Parse.Object.extend("Installation");
var q2 = new Parse.Query(install);
q2.equalTo("privacy", privateUserNo);
q2.equalTo("username", albumOwner);
q2.find({
success: function (results) {
if (!isApproved) {
Parse.Push.send({
where: q2, // Set our Installation query
data: {
alert: "New Photo uploaded by " + publicUser + " ,waiting for approval"
}
}, {
success: function () {
// Push was successful
console.log("Push success");
},
error: function (error) {
// Handle error
console.log("Push error");
}
})
}
},
error: function (error) {
console.log("Error: " + error.code + " " + error.message);
}
});
},
error: function (error) {
console.log("Error: " + error.code + " " + error.message);
}
});
} else if (!(request.object.get("createdAt").getTime() == request.object.get("updatedAt").getTime())) {
console.log("all case scenarios");
var getAlbumOwner1 = new Parse.Object.extend("Albums");
var q6 = new Parse.Query(getAlbumOwner1);
q6.equalTo("title", albumNameA);
q6.first({
success: function (results) {
albumOwner = results.get("creatorName");
var sendApproval = new Parse.Object.extend("Photos");
var q4 = new Parse.Query(sendApproval);
q4.descending("updatedAt");
q4.first({
success: function (results) {
var objectIDNeeded = results.id;
var isChanged = results.get("approved");
var currentUpdateTime = results.get("updatedTime");
console.log("Your Photo, " + publicUser + " ,has been approved by " + albumOwner);
var install = new Parse.Object.extend("Installation");
var q5 = new Parse.Query(install);
q5.equalTo("privacy", privateUserNo);
q5.equalTo("username", publicUser);
q5.find({
success: function (results) {
Parse.Push.send({
where: q5, // Set our Installation query
data: {
alert: "Your Photo has been approved by " + albumOwner
}
}, {
success: function () {
// Push was successful
console.log("Push success");
},
error: function (error) {
// Handle error
console.log("Push error");
}
})
},
error: function (error) {
console.log("Error: " + error.code + " " + error.message);
}
});
},
error: function (error) {
console.log("Error: " + error.code + " " + error.message);
}
});
},
error: function (error) {
console.log("Error: " + error.code + " " + error.message);
}
});
}
});
as the title mentioned, I have code like(part of):
var io = require('socket.io').listen(server);
io.sockets.on('connection', function(socket){
console.log("Connection " + socket.id + " accepted.");
socket.on('message', function(message){
console.log("Received message: " + message + " - from client " + socket.id);
});
socket.on('disconnect', function(){
console.log("Connection " + socket.id + " terminated.");
});
});
I have no idea what exactly they are, can someone give me some detail and example how to use them in real case? Such as how to refer to specific socket connection?
Thanks
After uploading a file, before I save it on the disk, I'm doing some validation.
If something fails, I want to show my custom error message to the user.
I've found something sililar here Uploadify: show error message from HTTP response
How to do this in MVC 3 ?
Tony,
Taken straight from ab mvc3 app that I'm working on right now:
<script type="text/javascript">
function initupLoadify() {
$("#fileInput").uploadify({
uploader: '#Url.Content("~/scripts/swf/uploadify.swf")',
script: '#Url.Action("Upload", "Home")',
cancelImg: '#Url.Content("~/Content/cancel.png")',
auto: true,
sizeLimit: 5500000,
fileDataName: 'fileData',
//scriptData: { 'propertyId': $("#PropertyID").val() },
buttonText: 'Add Schedule',
wmode: 'transparent',
//buttonImg: '#Url.Content("~/Content/button.png")', // make nice gradient image for button
onComplete: function (event, queueId, fileObj, response) {
$("#msg").html(response);
// do something
setTimeout(2000, window.location = '#Url.Action("Index")' + '?id=' + response);
return true;
},
onCancel: function (evt, queueId, fileObj, data) {
$("#msg").html("<br />Operation cancelled");
return true;
},
onOpen: function (evt, queueId, fileObj) {
$("#msg").html("<br />Upload in progress");
return true;
},
onError: function (event, queueId, fileObj, errorObj) {
$("#msg").html(fileObj.name + " was not uploaded ");
if (errorObj.status == 404)
$("#msg").html("Could not find upload script. Use a path relative to: " + "<?= getcwd() ?>");
else if (errorObj.type === "HTTP")
$("#msg").html("error " + errorObj.type + ": " + errorObj.status);
else if (errorObj.type === "File Size")
$("#msg").html(fileObj.name + " " + errorObj.type + " Limit: " + errorObj.info / 1000 + " KB");
else
$("#msg").html("error " + errorObj.type + ": " + errorObj.text);
}
});
};
</script>
hope this helps
Here is an MVC 3 example.
If you're using versions 3.0+ use onUploadComplete instead of onComplete (realize their parameters differ).