How to start different actions on server with two buttons on website? - javascript

Please think about: I'm a beginner and try to learn progamming with javascript.
My goal: I have two buttons on a website. Each of both has to start his own function on the server.
Thanks to various tutorials I manage to trigger an action on the server. But now I have to distinguish two buttons for different server actions.
server.js
var express = require('express');
var app = express();
app.set('view engine', 'jade');
app.use(express.bodyParser());
var tweetText = 'A lot of tweet text...';
var user = 'Lutz';
var account = '#name';
var relevance = 0;
var tweetID_str = 0;
var RTs = 0;
//Send data from client/browser to server
app.post('/', function (req, res) {
console.log('works');
console.log(req.body);
});
//Send data from server to client
app.get('/', function(req, res){
relevance = relevance + 1;
tweetID_str = tweetID_str + 2;
RTs = RTs +3;
console.log('relevance: '+relevance+' userbytwo: '+tweetID_str);
res.render('index', { tweetText: 'Text: '+tweetText, account: '#User: '+account, user: 'User: '+user, relevance: 'RT per follower: '+relevance, tweetID_str: 'ID_str: '+tweetID_str, RTs: 'RTs: '+RTs });
/* updated this line */
});
app.listen(3000);
index.jade
doctype html
html(lang="de")
head
body
div
div!= tweetText
div!= account
div
div!= user
div!= relevance
div!= tweetID_str
div!= RTs
form(method='post')
div
input(type='submit', id='good', value='good')
input(type='submit', id='bad', value='bad')
<!-- input(type='text', name='username') -->
I guess, I have to parse the website action. Depending on the result the server starts his action. I'm right or wrong? And what do I have to do, that my code works?

You could probably capture the id of the button after click and then call the necessary action based on the id received using jquery. For example you could do something like:
$('#good').click(function(){
// Do the action on server that you want to do on click of good button.
});
$('#bad').click(function(){
// Do the action on server that you want to do on click of bad button.
});
Not sure if this is what you wanted ? Let me know your exact needs for more help.
You can use JQuery AJAX call to invoke a method as below.
$(document).ready(function() {
$('#good').click(function(){
$.ajax({
url: "/home"
}).then(function(data) {
alert(data); // Do whatever you want to do with response.
});
});
});

Related

Simple Node.js chat program NOT using socket.io

I am trying to learn Node and build a simple chat application. It seems like everyone uses socket.io. I would like to understand how to do this on a more fundamental level using get and post.
Basically, all I want to do is have a form that takes an input and reposts it below the form for everyone to see.
This is what I have so far:
//Requirements
var express = require('express');
var app = express();
//GET
app.get('/', function (req, res) {
// res.send('Hello World!');
var response =
"<HEAD>"+
"<title>Chat</title>\n"+
"</HEAD>\n"+
"<BODY>\n"+
"<FORM action=\"/\" method=\"get\">\n" +
"<P>\n" +
"Enter a phrase: <INPUT type=\"text\" name=\"phrase\"><BR>\n" +
"<INPUT type=\"submit\" value=\"Send\">\n" +
"</P>\n" +
"</FORM>\n" +
"<P>phrase</P>\n"+
"</BODY>";
var phrase = req.query.phrase;
if(!phrase){
res.send(response);
}else{
res.send(response);
res.send(phrase);
}
});
//For testing
app.get('/test', function(req, res){
res.send('I am a robot');
console.log('told visiter I am a robot');
});
//Run the app
var server = app.listen(8080, function () {
var host = server.address().address;
var port = server.address().port;
console.log('App listening at http://%s:%s', host, port);
});
I've been trying a bunch of things, but I am pretty stumped.
Did you hear about messaging backend jxm.io?
It works with JXcore (open sourced fork of Node.JS). JXM itself is an open source project, which you can find on github: jxm.
It's really fast and efficient, you can check some tutorials. For example, below is minimal code, that you need to run on server-side:
var server = require('jxm');
server.setApplication("Hello World", "/helloworld", "STANDARD-KEY-CHANGE-THIS");
server.addJSMethod("serverMethod", function (env, params) {
server.sendCallBack(env, params + " World!");
});
server.start();
The client's part can be found here:
Browser Client (JavaScript)
JXM also supports Java clients (runs on android) and node clients.

Nodejs and webSockets, triggering events?

I am new to this, I built a standard web chat application and I see the power of nodejs, express, socket.io.
What I am trying to do is trigger events from a phone to a website, like a remote control. There is server javascript that listens to events from the client, and client javascript that triggers those events, this is how I understand it correct me if I am wrong.
I learned in the chat app I can send an object from anywhere, as long as they are connected to my server through a specific port http://my-server-ip:3000/. Basically all events are inside the index page, and the connection is index to server to index.
What I am trying to learn is how to trigger events from an external page, I've seen things like http://my-server-ip:3000/ws or something like that, the idea is to connect to a mobile interface that isn't the actual index or website itself, but this interface communicates with the node server using it as a dispatcher to trigger events on the main index page.
Basically what I have learned was index to server to index. I am not sure how I can go custom-page to server to index.
I see that in my app.js, my understanding is that the socket listens to sends which is on the client then it emits the message.
io.sockets.on('connection', function (socket) {
socket.on('sends', function (data) {
io.sockets.emit('message', data);
});
});
I tried creating a test.html that has a button on it, I tried listening to it, here is a screen shot.
Here is my client code
window.onload = function() {
var messages = [];
var socket = io.connect('http://my-server-ip:3000/');
var socketTwo = io.connect('http://my-server-ip:3000/test.html');
var field = document.getElementById("field");
var sendButton = document.getElementById("send");
var content = document.getElementById("content");
var name = document.getElementById("name");
var trigBtn = document.getElementById("trigger-btn");
socket.on('message', function (data) {
if(data.message) {
messages.push(data);
var html = '';
for(var i=0; i<messages.length; i++) {
html += '<b>' + (messages[i].username ? messages[i].username : 'Server') + ': </b>';
html += messages[i].message + '<br />';
}
content.innerHTML = html;
} else {
console.log("There is a problem:", data);
}
});
//FROM DEMO
// sendButton.onclick = sendMessage = function() {
// if(name.value == "") {
// alert("Please type your name!");
// } else {
// var text = field.value;
// socket.emit('send', { message: text, username: name.value });
// field.value = "";
// }
// };
//I include this javascript with test.html and trigger
//this button trying to emit a message to socketTwo
trigBtn.onclick = sendMessage = function() {
socketTwo.emit('send', { message: 'String test here' })
}
}
I am sure that is all wrong, but hopefully this makes sense and someone can help me trigger events from another page triggering to the index.
Here is my app.js server code
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, http = require('http');
var app = express();
var server = app.listen(3000);
var io = require('socket.io').listen(server); // this tells socket.io to use our express server
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.static(__dirname + '/public'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
});
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('/', routes.index);
app.get('/test.html', function(req, res) {
res.send('Hello from route handler');
});
io.sockets.on('connection', function (socket) {
socket.emit('message', { message: 'welcome to the chat' });
socket.on('send', function (data) {
io.sockets.emit('message', data);
});
});
All code posted above is just testing cookie cutter code, I am learning from scratch so the above can be totally changed, it's just there as a starter point.
This is so cool I got it to work, so my logic was correct. There were just a few things I was missing. Here it is.
I am not going to post all the server side javascript code, but here is the main logic after listening to the port etc.
// Set a route and in a very dirty fashion I included a script specific
// for this route, earlier I was using one script for both route.
// I also forgot to include the socket.io hence the error in the image above.
app.get('/test', function(req, res) {
res.send('<script src="/socket.io/socket.io.js"></script><script type="text/javascript" src="javascripts/trigger.js"></script><button id="test" class="trigger-btn">Trigger</button>');
});
// This listens to `send` which is defined in the `test` route
// Upon this action the server emits the message which
// is defined inside the index main route I want stuff displayed
io.sockets.on('connection', function (socket) {
socket.on('send', function (data) {
io.sockets.emit('message', data);
});
});
Here is what the index client,js script looks like
window.onload = function() {
var messages = [];
var socket = io.connect('http://my-server-ip:3000');
var content = document.getElementById("content");
socket.on('message', function (data) {
if(data.message) {
messages.push(data);
var html = '';
for(var i=0; i<messages.length; i++) {
html += '<b>' + (messages[i].username ? messages[i].username : 'Server') + ': </b>';
html += messages[i].message + '<br />';
}
content.innerHTML = html;
} else {
console.log("There is a problem:", data);
}
});
}

When namespacing I receive a "cannot GET error" displayed in browser

I'm using namespaces to differentiate between version of my socket.io chat app, and I'm having trouble with a "cannot GET error displayed in browser."
I plan on continually updating a chat app I made in a basic socket.io tutorial, and I want to be able to launch any version of it at any time. I'm going to do this by the use of namespaces. When I launch my app in browser at the location myserverlocation/v0.0.1 to access version 0.0.1 of my app, I get an error that states cannot GET '/v0.0.1'.
This is my server code:
var app = require('express')(),
server = require('http').Server(app),
io = require('socket.io').listen(server),
chat = io.of('/v0.0.1');
server.listen(80);
// routing
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
// usernames which are currently connected to the chat
var usernames = {};
chat.on('connection', function (socket) {
// when the client emits 'sendchat', this listens and executes
socket.on('sendchat', function (data) {
// we tell the client to execute 'updatechat' with 2 parameters
io.sockets.emit('updatechat', socket.username, data);
});
// when the client emits 'adduser', this listens and executes
socket.on('adduser', function(username) {
// we store the username in the socket session for this client
socket.username = username;
// add the client's username to the global list
usernames[username] = username;
// echo to client they've connected
socket.emit('updatechat', 'SERVER', 'you have connected');
// echo globally (all clients) that a person has connected
socket.broadcast.emit('updatechat', 'SERVER', username + ' has connected');
// update the list of users in chat, client-side
io.sockets.emit('updateusers', usernames);
});
// when the user disconnects.. perform this
socket.on('disconnect', function() {
// remove the username from global usernames list
delete usernames[socket.username];
// update list of users in chat, client-side
io.sockets.emit('updateusers', usernames);
// echo globally that this client has left
socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has disconnected');
});
});
And this is my client code:
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script>
var socket = io.connect('myserverlocation');
var chat = socket.of('/v0.0.1');
// on connection to server, ask for user's name with an anonymous callback
chat.on('connect', function(){
// call the server-side function 'adduser' and send one parameter (value of prompt)
chat.emit('adduser', prompt("What's your name?"));
});
// listener, whenever the server emits 'updatechat', this updates the chat body
chat.on('updatechat', function(username, data) {
$('#conversation').append('<b>' + username + ':</b> ' + data + '<br>');
});
// listener, whenever the server emits 'updateusers', this updates the username list
chat.on('updateusers', function(data) {
$('#users').empty();
$.each(data, function(key, value) {
$('#users').append('<div>' + key + '</div>');
});
});
// on load of page
$(function(){
// when the client clicks SEND
$('#datasend').click( function() {
var message = $('#data').val();
$('#data').val('');
// tell server to execute 'sendchat' and send along one parameter
chat.emit('sendchat', message);
});
// when the client hits ENTER on their keyboard
$('#data').keypress(function(e) {
if(e.which == 13) {
$(this).blur();
$('#datasend').focus().click();
}
});
});
</script>
<div style="float:left;width:100px;border-right:1px solid black;height:300px;padding:10px;overflow:scroll-y;">
<b>USERS</b>
<div id="users"></div>
</div>
<div style="float:left;width:300px;height:250px;overflow:scroll-y;padding:10px;">
<div id="conversation"></div>
<input id="data" style="width:200px;" />
<input type="button" id="datasend" value="send" />
</div>
My chat app works fine without the use of namespaces, at myserverlocation/. I cannot figure out why I keep getting this error. After some investigation I think my usage of io.of() is incorrect, but I cannot seem to fix the problem. I'm not sure if my problem lies in the server code, the client code, or both.
Edit: After more investigation, I think my problem lies in the follow segment of code (though I could be mistaken):
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
Edit2: The problem did in fact lie in the code segment above. I should have been sending my whole /Chat directory as static content instead of using res.sendfile() to send one file. I will formally answer my own question when stackoverflow lets me (I have to wait 8 hours to answer my own question).
I managed to find what my problem was. The problem lied in the following section of code:
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
I was sending one particular file upon connection to my server, when I should be sending my entire /Chat directory as static content. This way, I can chose what version of my chat app I would like to launch. I managed to do this by changing a few lines of code in my server code:
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
server.listen(80);
// Chat directory
app.use(express.static('/home/david/Chat'));

setTimeout in node.js - javascript

Here I have a code for sum 3 numbers i+j+k but I waht to know how to configure server file to work with setTimeout function... is there some restriction?
so, here is mycode:
index.jade
!!! 5
html
head
title Test
body
form(name='form1', method='post', action='')
label(for='1')
input#1(type='text', name='1')
label(for='2')
input#2(type='text', name='2')
label(for='3')
input#3(type='text', name='3')
input(name='submit', type='button', value='submit')
span #{result}
app.js
var express = require('express');
app = express.createServer();
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.set("view options", { layout: false });
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.use(express.bodyParser());
app.get('/', function(req, res){
var result;
res.render('index', {result: ''});
});
app.post('/', function(req, res){
var i = req.param('1', 0);
i = parseInt(i);
var j = req.param('2', 0);
j = parseInt(j);
var k = req.param('3', 0);
k = parseInt(k);
var r = i+j+k;
res.render('index', {result:r});
});
app.listen(3010);
How etc. to block user action (click,doubleclick,rightclick) and show him a div with text "You can do any action" in first 5 seconds and after that user can do action but after 60 seconds again can't do any action... Can I do this with setTimout function or HOW???
sorry for my english
You cannot do this on the server side. You have to insert a client side javascript that blocks the interaction and unblocks it again after 5 sec.
The code for doing this on the client side would be something like this:
// this code should be executed when the client receives a message from the server.
var overlay = document.getElementById("your-element-id");
overlay.style.visibility = "visible";
window.setTimeout(function () {
overlay.style.visibility = "hidden";
}, 5000);
You should take the following steps to achieve what you want:
1. The user loads the page.
2. The user receives a message from the server, stating that he is being synchronized
3. Then either after a specified time or after another message from the server you unblock the user
4. Finally you start the game

In Express.js, how do I make my template display the flash messages?

app.get('/',function(req,res){
res.render('home'); // I want the template to be able to access the flash message..
});
app.get('/go',function(req,res){
req.flash("info", "You went GO, and got redirected to home!");
res.redirect('/');
});
The user first goes to "/go". After that, he will be redirected to "/" and I want a flash message to show as a javascript alert.
How can I do that?
Add it as a local to your call to render:
res.render("home", {info: req.flash("info")});
And use it in your template:
#flash
p= info
You can use express dynamic helpers to make your life easier.
app.dynamicHelpers({flashMessages: function(req, res) {
var html = ""
, flash = req.flash();
['error', 'info'].forEach(function(type) {
if(flash[type]) {
flash[type].forEach(function(message) {
html += "<div class='alert " + type + "'>" + message + "</div>";
});
}
});
return html; }});
and in your layout (ejs example)
<body><%- flashMessages %><%- body %></body>
app.dynamicHelpers({flash: function(req, res){return req.flash();}});
Now you have access at the flash object in you view. No HTML in your logic and no need to add all the params in every routes.
For me, I use the following code to display flash message:
In app.js
app.use(function (req, res, next) {
req.session.message = req.session.message || { error: [], success: [], info: [] };
app.locals.message = req.session.message;
}
In your user.js route:
app.post('/users/new', function (req, res, next) {
//...
// do some work
req.session.message.info.push('Account created successfully');
res.redirect('/login');
});
Then, create a message.jade in view that you could be included into other views:
In message.jade
- var i
- if (message.error && message.error.length)
.alert.alert-warning.alert-dismissable
button.close(type="button", data-dismiss="alert", aria-hidden="true") ×
- for (i = 0; i < message.error.length; i++)
.center!= message.error[i]
- if (message.info && message.info.length)
.alert.alert-info.alert-dismissable
button.close(type="button", data-dismiss="alert", aria-hidden="true") ×
- for (i = 0; i < message.info.length; i++)
.center!= message.info[i]
- message.info = message.error = [] // REMEMBER to reset messages to an empty array
Had a similar issue, solution seems to be:
req.flash('error', 'validation failed');
res.redirect('back');
Using back seems to maintain the flash message, where as redirecting to the same route looses it.
If you're using Express 3, the built-in flash functionality has been removed. To get the same functionality, you'll want to install the connect-flash module, then add the code from this Gist just after you initialize your sessions and before app.use(app.router);: https://gist.github.com/3070950

Categories

Resources