How does routing affect form validation - node.js

I'm working on my first project in node and I'm trying to validate the a form using jQuery validation http://jqueryvalidation.org
I have it working on jsfiddle http://jsfiddle.net/o16u2fLq/ , but in my project my form is submitting without the validations. I think it has to do with how I'm routing the form, but I'm not sure what the problem is.
Here are my routes:
var express = require('express');
var router = express.Router();
var Greeting = require('../models/greetings');
router.get('/', function(req, res) {
Greeting.getGreetings(req).then(function (greetings) {
res.render('index', { greetings: greetings });
res.redirect('/');
});
});
router.post('/greeting', function(req, res){
console.log(req.body);
Greeting.createGreeting(req, res);
res.redirect('/');
Greeting.getGreetings(req).then(function (greetings) {
res.render('index', { greetings: greetings });
});
});
module.exports = router;
I've tried playing around with the routes, but nothing was working. How am I able to validate the form before posting the submission?
Edit:
html as requested
<!DOCTYPE html>
<html>
<head>
<link href="./bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="./bower_components/jquery-ui/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" href="./css/custom.css">
</head>
<body>
<div class="container-fluid" style="padding-top:20px">
<form action="/greeting" method="Post" enctype="application/x-www-form-urlencoded" class="form-horizontal col-lg-4" id="welcome">
<div class="form-group">
<label for="guest" class="col-lg-3 control-label">Guest Name: </label>
<div class="col-lg-9">
<input type="text" class="form-control" id="guest" name="guest">
</div>
</div>
<div class="form-group">
<label for="message" class="col-lg-3 control-label">Message: </label>
<div class="col-lg-9">
<textarea class="form-control" id="message" name="message" rows="3"></textarea>
</div>
</div>
<div class="form-group">
<label for="datepicker" class="col-lg-3 control-label">Date: </label>
<div class="col-lg-9">
<input type="text" class="form-control" name="display_date" id="datepicker">
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-3 col-lg-9">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
<div class="col-lg-offset-2 col-lg-5">
<table class="table">
<thead>
<th>
Guest
</th>
<th>
Message
</th>
</thead>
<tbody>
<% for(var i=0; i < greetings.length; i++) { %>
<tr>
<td><%= greetings[i].guest %></td>
<td><%= greetings[i].message %></td>
</tr>
<% } %>
</tbody>
</table>
</div>
</div>
</body>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<script src="./bower_components/jquery-ui/jquery-ui.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.14.0/jquery.validate.js"></script>
<script src="./scripts/custom.js"></script>
<script>
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
</html>

in my openion
create a validator.js file
add all validations
in app.js file first you point to the valdator, after go to router folder

Related

How to make my update button work correctly

I am making a todolist app using express, mongoose, mongodb, bootstrap. When I hit my update button to update a task it just makes a duplicate of the task that i'm trying to update. How would I go about making my update button update the original task?
Here are some screenshots on what happens when I try to update :
https://i.stack.imgur.com/t11OG.jpg - here I created a task "make breakfast".
https://i.stack.imgur.com/ijt98.jpg - here I hit the yellow update button and I am updating the task from "make breakfast" to "make lunch".
https://i.stack.imgur.com/V4RCe.jpg - here when I hit the green update button it creates a separate task instead of updating the original "make breakfast" task.
My routes and my ejs for the home page are below:
I can also show the ejs for updating a task as well.
Thanks
const express = require("express");
const { route } = require("express/lib/application");
const router = express.Router();
const mongoose = require("mongoose");
const Todoinfo = require("../models/infoSchema");
router.get("/", async (req, res) => {
// get all todos
const allTodos = await Todoinfo.find({}).sort("-date");
res.render("home", { allTodos });
});
router.post("/", async (req, res) => {
// add a todo
const newTodo = new Todoinfo(req.body); // create a new todo
await newTodo.save((err) => {
// save the new todo
if (err) {
res.send("Not updated");
}
});
//res.redirect("/");
});
router.get("/:id/delete", async (req, res) => {
// delete a todo
const todoDelete = await Todoinfo.findByIdAndDelete(req.params.id); // find the todo by id and delete it?
res.redirect("/"); // redirect to home page
});
router.get("/:id/finish", async (req, res) => {
// finish a todo (change status to completed)
const todoDelete = await Todoinfo.findByIdAndUpdate(req.params.id, {
progress: "Completed",
});
res.redirect("/");
});
router.get("/:id/update", async (req, res) => {
// update a todo (change status to in progress)
const updateTodo = await Todoinfo.findById(req.params.id); // find the todo by id and update it?
res.render("update", { updateTodo }); // render the update page with the todo
});
router.get("/:id/update/final", async (req, res) => {
// update a todo (change status to finished)
const updateTodo = await Todoinfo.findByIdAndUpdate(req.params.id, {
// find the todo by id and update it?
description: req.body.description, // update the description of the todo with the new description
});
res.redirect("/");
});
module.exports = router;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<title>Todo App</title>
</head>
<body>
<section class="vh-100" style="background-color: #eee ">
<div class="container py-5 h-100">
<div class="row d-flex justify-content-center align-items-center h-100">
<div class="col col-lg-12 col-xl-g">
<div class="card rounded-3">
<div class="card-body p-4">
<h4 class="text-center my-3 pb-3 text-primary ">My Todo App</h4>
<form class="row row-cols-lg-auto g-3 justify-content-center
align-items-center mb-4 pb-2" action="/" method="POST">
<div class="col-12">
<div class="form-outline">
<input type="text" id="form1" class="form-control" name="description" />
<label class="form-label" for="form1">Create a new task </label>
</div>
</div>
<div class="col-12">
<button type="submit" class="btn btn-primary mb-4">Add</button>
</div>
</form>
<table class="table mb-4">
<thead>
<tr>
<th scope="col">Item No.</th>
<th scope="col">Todo Item</th>
<th scope="col">Action</th>
<th scope="col">Status</th>
</tr>
</thead>
<tbody>
<% for(let i= 0; i <allTodos.length; i++) { %>
<tr>
<% let z= i + 1 %>
<th scope="row"><%= z %></th>
<% if (! allTodos[i].progress.localeCompare(" Completed" )) { %>
<td class="text-decoration-line-through"> <%=
allTodos[i].description %> </td>
<%} else {%>
<td> <%= allTodos[i].description %> </td>
<%}%>
<td> <%= allTodos[i].progress %> </td>
<td>
<button type="submit" class="btn btn-danger ms-1 mb-1">Delete</button>
<% if (! allTodos[i].progress.localeCompare(" Completed"))
{ %>
<%} else {%>
<a href="/<%= allTodos[i]._id %>/finish" class="text-decoration-none">
<button type="submit" class="btn btn-success ms-1 mb-1">Finished</button></a>
<button type="submit" class="btn btn-warning ms-1 mb-1">Update</button>
<% } %>
</td>
</tr>
<% } %>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</section>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
</body>
</html>

connects to server but database is not created and not saving chat history. i am using nodejs, mongodb to save and robomongo to view

i developed a client side application and have two html files
This is index.html and after filling form redirect to chat.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Join | chatApp</title>
<meta name = "viewport" content ="width=deveice-width, initial-scale=1, user-scalable =no ">
<link rel="stylesheet" href="/css/style.css">
</head>
<body class ="centered-form">
<div class ="centered-form__form">
<form action="/chat.html">
<div class="form-field">
<h3>want to Join a Chat</h3>
</div>
<div class="form-field">
<label>Name</label>
<input type="text" name="name" autofocus/>
</div>
<div class="form-field">
<label>Room Name</label>
<input type="text" name="room"/>
</div>
<div class="form-field"></div>
<button>Join</button>
</form>
</div>
</body>
</html>
This is the chat.html and wants to save all the chat history in a database.
<body class="chat">
<div class="chat__sidebar">
<h3>people</h3>
<div id="users">
</div>
</div>
<div class="chat__main">
<ol id="messages" class="chat__messages"></ol>
<div class="chat__footer">
<form id="message-form" method ="post" action="/add">
<input type="text" name="message" placeholder="message" autofocus autocomplete ="off"/>
<button>send</button>
</form>
<button id="send-location">send location</button>
</div>
</div>
<script id="message-template" type="text/template">
<li class="message">
<div class="message__title">
<h4>{{from}}</h4>
<span>{{createdAt}}</span>
</div>
<div class="message__body">
<p>{{text}}</p>
</div>
</li>
</script>
<script id="location-message-template" type="text/template">
<li class="message">
<div class="message__title">
<h4>{{from}}</h4>
<span>{{createdAt}}</span>
</div>
<div class="message__body">
<p> My current location </p>
</div>
</li>
</script>
</body>
code to save in a database
var express = require("express");
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
var mongoose =require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/chatApp');
var nameSchema = new mongoose.Schema({
message:{type: String}
});
var User = mongoose.model("User", nameSchema);
app.get('/', (req, res)=>{
res.sendFile(__dirname, '/public/chat.html');
});
app.post('/add', function (req, res){
var message = req.body.message;
var myData = new User();
myData.message = message;
myData.save().then((item)=>{
res.send('item saved');
},(err)=>{
res.status(400).send('unable to save');
});
});

how to display a single prouct from database in mongodb and node.js

we have created a e-commerce project in that while clicking on categories in UI it will renders to category page in that page it has show one product of each subcategory
i have written the code in which the entire products with the specific category name is displaying how i can remove the extra products as of now i required only one product of each sub category of the particular category
the routing code is
router.get("/shop/:category_name", function(req, res){
//querystring
var url = require('url');
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
var viewModel = {
breadCrumb: [],
categories : [],
featuredProducts :[],
products : [],
};
viewModel.breadCrumb.push({
name : 'Home',
class : 'breadcrumb-ordinary'
});
viewModel.breadCrumb.push({
name : req.params.category_name,
class : 'breadcrumb-active'
});
async.parallel({
categories: function(cb){
Category.find({}, cb);
},
categories1:function(cb){
Category.find({category_name:req.params.category_name}, cb);
}
}, function(err, results) {
if (err) throw err;
viewModel.categories1=results.categories1;
viewModel.categories=results.categories;
res.render('shop/prod_grid',viewModel);
});
});
the view UI code is
<!doctype html>
<html lang="en-US"> <!--<![endif]-->
<head>
</head>
<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
<link rel="stylesheet" href="../../../shop-plugins/css/jplist-pagination.css">
<link rel="stylesheet" href="../../../shop-plugins/css/breadcrumb.css">
<body>
{{> shop/header}}
<!-- BAR -->
<div class="shipping-wrap">
<div class="container">
<div class="row">
<div class="span12">
<ul>
<li>
{{#each breadCrumb}}
{{#if #first}}
<a href="/" class="{{class}}">{{name}}
{{else}}
<a class="{{class}}">{{name}}
{{/if}}
{{#if #last}}
{{else}}
<i class="fa fa-angle-double-right"></i></a>
{{/if}}
{{/each}}
</li>
</ul>
</div>
</div>
</div>
</div>
<!-- BAR -->
<!-- PRODUCT-OFFER -->
<div class="product_wrap">
<div class="container">
<div class="row">
<div id="span9" class="span9 product-grid">
<div id="products" class="box jplist jplist-grid-view">
<div class="jplist-panel box jplist-panel-top">
<div
class="jplist-drop-down"
data-control-type="items-per-page-drop-down"
data-control-name="paging"
data-control-action="paging">
<ul id="per-pages">
<li><span data-number="3">3 per page</span></li>
<li><span data-number="6" data-default="true">6 per page</span></li>
<li><span data-number="9">9 per page</span></li>
<li><span data-number="12">12 per page</span></li>
</ul>
</div>
<div
class="jplist-drop-down"
data-control-type="sort-drop-down"
data-control-name="sort"
data-control-action="sort">
<ul id="sorting">
<li><span data-path="default">Sort By</span></li>
<li><span data-path=".brand" data-order="asc" data-type="text">Brand A-Z</span></li>
<li><span data-path=".brand" data-order="desc" data-type="text">Brand Z-A</span></li>
<li><span data-path=".cost" data-order="asc" data-type="number">Cost Low-High</span></li>
<li><span data-path=".cost" data-order="desc" data-type="number">Cost High-Low</span></li>
</ul>
</div>
<div
class="jplist-label"
data-type="Page {current} of {pages}"
data-control-type="pagination-info"
data-control-name="paging"
data-control-action="paging">
</div>
<div
class="jplist-views"
data-control-type="views"
data-control-name="views"
data-control-action="views"
data-default="jplist-grid-view">
</div>
</div>
{{#each subcategoryprod}}
<div>
<ul>
<li>{{subcategory}}</li>
</ul>
</div>
{{/each}}
<!--category wise products-->
<div id="jp-panel" class="list box text_shadow">
{{#each subcategoryprod}}
<div id="jp-panel-item" class="list-item box">
<div class="span3 product">
<div>
<figure>
{{#each image}}
{{#if #first}}
<img src="../../../uploads/products/{{../_id}}/{{img}}" alt="" onerror="this.src='../../../shop-images/coming-soon.png'">
<div class="overlay">
</div>
{{/if}}
{{else}}
<img src="../../../shop-images/coming-soon.png" alt="">
<div class="overlay">
</div>
{{/each}}
</figure>
<div class="detail">
<span name="retailprice" class="cost">₹{{RetailPrice}}</span>
<span>{{colour}}</span>
<h4 class="brand">{{brand}}</h4>
<span>{{Description}}</span>
<div class="icon">
</div>
</div>
</div>
</div>
</div>
{{/each}}
</div>
<div class="box jplist-no-results text-shadow align-center">
<p> No results Found</p>
</div>
<div class="jplist-panel box panel-bottom">
<div
class="jplist-label"
data-type="{start} - {end} of {all}"
data-control-type="pagination-info"
data-control-name="paging"
data-control-action="paging">
</div>
<div
class="jplist-pagination back-top"
data-control-animate-to-top="true"
data-control-type="pagination"
data-control-name="paging"
data-control-action="paging">
</div>
</div>
</div>
</div>
<div class="span3">
<div class="row">
</div>
<div id="sidebar">
<div class="widget">
<h4>Price Filter</h4>
<div class="price-range">
<div id="slider-range"></div>
<p class="clearfix">
<input type="text" id="amount" readonly />
<input type="text" id="amount2" readonly />
</p>
</div>
</div>
<div class="widget">
<h4>BRANDS</h4>
<div id="">
<div class="brands">
<input type='text' id='txtList' onkeyup="searchBrand(this)" placeholder="search brands here....." />
<!-- <ul id="fromList" class="myid"> -->
{{#each products}}
<ul id="fromList" class="myid">
<li> <input type="checkbox" id="{{brand}}" class="brandFilterCheckBox pull-right" align="center"/> <label for="{{brand}}">{{brand}}<label></li>
</ul>
{{/each}}
<!-- </ul> -->
</div>
</div>
</div>
</div>
<div class="widget">
<h4>CATEGORIES</h4>
<div id="accordion">
{{#each categories}}
<h5>{{category_name }}</h5>
<div>
<ul>
{{#each subcategories1}}
<li>{{subcategory_name}}</li>
{{/each}}
</ul>
</div>
{{/each}}
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Featured Products -->
<div class="container" style="margin-top:10px">
<div class="row heading-wrap">
<div class="span12 heading">
<h2>Featured Products <span></span></h2>
</div>
</div>
<div class="row similar_products">
<div id="feat_prod">
{{#each featuredProducts}}
<div class="span3 product">
<figure>
{{#each image}}
{{#if #first}}
<img src="../../../uploads/products/{{../_id}}/{{img}}" alt="">
<div class="overlay">
</div>
{{/if}}
{{/each}}
</figure>
<div class="detail">
<span>₹{{RetailPrice}}</span>
<h4>{{product_name}}</h4>
<span>{{Description}}</span>
</div>
</div>
{{/each}}
</div>
</div>
</div>
<!-- PRODUCT-OFFER -->
<!-- FOOTER -->
{{> shop/footer}}
<script type="text/javascript" src="../../../shop-plugins/js/jplist-pagination.js"></script>
<script src="../../../bootstrap/js/star.min.js"></script>
<script src="../../../shop-plugins/js/jquery.paginate.js"> </script>
<script>
$(function(){
$('#feat_prod').paginate();
});
</script>
<script>
$(document).ready(function(){
$('#products').jplist({
itemsBox: '.list'
,itemPath: '.list-item'
,panelPath: '.jplist-panel'
});
});
</script>
<script>
$('document').ready(function(){
$("#slider-range").slider({change : function(event,ui){
var lowerLimit=$("#amount").val();
var numberLowerLimit=Number(lowerLimit.substring(1,lowerLimit.length));
var upperLimit=$("#amount2").val();
upperLimit=upperLimit.substring(1,upperLimit.length);
var numberUpperLimit=Number(upperLimit.replace("₹",""));
console.log("LOWER LIMIT :"+lowerLimit+" UPPER LIMIT :"+upperLimit);
$(".cost").each(function(){
var rowUnitCost=$(this).text();
var unitCost=Number(rowUnitCost.substring(1,rowUnitCost.length));
if(unitCost<numberLowerLimit || unitCost>numberUpperLimit){
var hiddingBox=$(this).parents(".list-item");
/*hiddingBox.removeClass("list-item").addClass("rafsal-test");*/
hiddingBox.hide();
console.log("Values IN:"+unitCost);
}
else{
var hiddingBox=$(this).parents(".list-item");
if(hiddingBox.attr('id')==undefined || hiddingBox.attr('id')=="undefined"){
hiddingBox=$(this).parents(".rafsal-test");
hiddingBox.addClass("list-item").removeClass("rafsal-test");
}
hiddingBox.show();
console.log("Values OUT:"+unitCost);
}
$('#products').jplist({
itemsBox: '.list' ,
itemPath: '.list-item' ,
panelPath: '.jplist-panel'
});
});
}
});
// Brand Filter
$(".brandFilterCheckBox").on('click',function(){
$(".brand").each(function(){
var hiddingBox=$(this).parents(".list-item");
hiddingBox.removeClass("list-item").addClass("rafsal-test");
hiddingBox.hide();
});
$(".brandFilterCheckBox").each(function(){
if($(this).prop("checked")){
var filterBrand=$(this).attr("id");
$(".brand").each(function(){
var unitBrandName=$(this).text().trim();
if(unitBrandName== filterBrand){
console.log(unitBrandName);
var hiddingBox=$(this).parents(".list-item");
if(hiddingBox.attr('id')==undefined || hiddingBox.attr('id')=="undefined"){
hiddingBox=$(this).parents(".rafsal-test");
hiddingBox.addClass("list-item").removeClass("rafsal-test");
}
hiddingBox.show();
}
});
$('#products').jplist({
itemsBox: '.list' ,
itemPath: '.list-item' ,
panelPath: '.jplist-panel'
});
}
});
})
var textCheck="##";
removeDuplicateBrands()
});
function removeDuplicateBrands(){
var textCheck="##";
$(".brandFilterCheckBox").each(function(){
$(this).attr('id');
if(textCheck.indexOf("##"+$(this).attr('id')+"##")==(-1)){
textCheck=textCheck+$(this).attr('id')+"##";
}
else{
$(this).parent("li").hide();
}
});
}
</script>
<script>
function searchBrand(element) {
var value = $(element).val();
$("#fromList li").each(function () {
if ($(this).text().search(value) > -1) {
$(this).show();
$(this).prevAll('.header').first().show();
} else {
$(this).hide();
}
});
removeDuplicateBrands();
}
</script>
</body>
so i am posting a photo in which my output is there it contains all products of a specified category i need only one product from each sub category of the specified category and the image contains four products of protection category and two sub categories air freshners and Head unit , air freshners contains three products i need to display only one from airfreshner and one from head unit in which we need
In Your Router Code, Edit this section
categories1:function(cb){
Category.find({category_name:req.params.category_name}, cb);
}
Change the above to this
categories1:function(cb){
Category.findOne({category_name:req.params.category_name}, cb);
}
That should solve it for you.

MEAN + Passport: login failed, don't redirect just show an error in the same modal

Just like in the question: how can I use Passport without redirecting user to the /signin or /home when he fails his authentication?
To login user has to click on "login" button, a modal will pop up, he fills the data. If he succeeds he is redirected to the homepage. But if he isn't I want to show him the flash message in the same modal without redirecting. It kinda works because if you fail to login and click "login" again the error message will be shown. But I don't want to force users to constantly click it to check what went wrong.
They should fail, see the error, fill in new data and click submit again.
home.server.route.js:
var user = require(__dirroot + '/app/controllers/user.server.controller.js')
var passport = require('passport')
module.exports = function(app) {
var home = require(__dirroot + '/app/controllers/home.server.controller.js')
app.get('/', home.render)
app.route('/home/signin')
.get(user.renderSignin)
.post(passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/',
failureFlash: true
}))
}
home.server.controller.js:
exports.render = function(req, res) {
res.render('home', {
title: 'erpeg',
messages: req.flash('error') || req.flash('info'),
srvuser: req.user ? req.user : null,
cltuser: JSON.stringify(req.user)
})
}
home.ejs:
<!doctype>
<html>
<head>
<title></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="lib/foundation/css/normalize.css">
<link rel="stylesheet" href="lib/foundation/css/foundation.css">
<script src="https://www.google.com/recaptcha/api.js"></script>
<script src="lib/jquery/dist/jquery.min.js"></script>
</head>
<body>
<nav class="top-bar">
<ul class="title-area">
<li class="name">
<h1>
<a href="/">
<%= title %>
</a>
</h1>
</li>
<li class="toggle-topbar menu-icon">
<a href="#">
<span>Menu</span>
</a>
</li>
</ul>
<section class="top-bar-section">
<ul class="right">
<% if (srvuser) { %>
<% if(srvuser.rank == "administrator") { %>
<li>
</li>
<% } %>
<li>
<a href="/profile">
<%= srvuser.fullName %>
</a>
</li>
<li>
wyloguj
</li>
<% } else { %>
<li>
rejestruj
</li>
<li class="active">
zaloguj
</li>
<% } %>
</ul>
</section>
</nav>
<div id="signinModal" class="reveal-modal" data-reveal aria-labelledby="signinTitle" aria-hidden="true" role="dialog">
<% for (var i in messages) { %>
<div data-alert class="alert-box warning">
<p>
<%= messages[i] %>
</p>
×
</div>
<% } %>
<h1 id="signinTitle">logowanie</h1>
<form action="/home/signin", method="post">
<div class="row">
<div class="large-12 columns">
<input type="text" name="username" id="username" placeholder="nazwa użytkownia">
</div>
</div>
<div class="row">
<div class="large-12 columns">
<input type="password" name="password" id="password" placeholder="password">
</div>
</div>
<div class="row">
<div class="large-12 columns">
<input class="button expand" type="submit" value="zaloguj">
</div>
</div>
</form>
</div>
<script src="lib/modernizr/modernizr.js"></script>
<script src="./lib/foundation/js/foundation.min.js"></script>
<script src="lib/angular/angular.min.js"></script>
<script src="lib/angular-route/angular-route.min.js"></script>
<script src="lib/angular-resource/angular-resource.min.js"></script>
<script src="/user/user.client.module.js"></script>
<script src="/user/services/authentication.client.service.js"></script>
<script src="/game/game.client.module.js"></script>
<script src="/game/controllers/game.client.controller.js"></script>
<script src="/game/services/game.client.service.js"></script>
<script src="/game/config/game.client.route.js"></script>
<script src="application.js"></script>
</body>
</html>
PS: I had it working with separate pages but since I am changing my template engine from Jade to EJS I thought I will do it more elegantly (inside a modal). Any help?

No data send with socket.io

I have to send data using socket.io.when a user enter his login and a password,he will be redirect to index.ejs and the username will be send to the server.
route.js (I mentioned only the part of the script not the hole script to show that when the login and password are correct a user get an index page and the userobject send to the index):
var index = function(req, res, next) {
if(!req.isAuthenticated()) {
res.redirect('/signin');
} else {
var user = req.user;
if(user !== undefined) {
user = user.toJSON();
}
res.render('index', {title: 'Home', user: user});
}
};
app.js:
io.sockets.on('connection', function (socket) {
socket.on("new_user",function(user1){
console.log("a new user is connected",user1);
var current_date=new Date();
var date=current_date.toString();
ex.user_connect(user1,date);
});
});
index.ejs:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width ,initial-scale=1.0" />
<title><%= title %></title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="style/style.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="js/bootstrap.js"></script>
</head>
<body>
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="/">HomePage</a>
</div>
<div>
<ul class="nav navbar-nav navbar-right">
<li><%= user.username%></li>
<li><span class="glyphicon glyphicon-log-out"></span> Sign out</li>
</ul>
</div>
</div>
</nav>
<div class="container">
<div class="jumbotron">
<div class="row">
<div class="col-sm-6">
<div class="container">
<h2>Led1</h2>
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-default btn-lg" id="led1" align="center">check it</button>
<!-- Modal -->
<div class="modal fade" id="model_led1" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header" style="padding:35px 50px;">
<button type="button" class="close" data-dismiss="modal" id="close">×</button>
<h4><span class="glyphicon glyphicon-lock"></span> Settings</h4>
</div>
<div class="modal-body" style="padding:40px 50px;">
<form role="form">
<img src="style/images/led.png" id="led" class="img-responsive"/>
<button type="button" class="btn btn-success btn-block" id="led1_activ"><span class="glyphicon glyphicon-off"></span> Activate</button>
<button type="button" class="btn btn-success btn-block" id="led1_desactiv"><span class="glyphicon glyphicon-off"></span> Desactivate</button>
</form>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-danger btn-default pull-left" data-dismiss="modal" id="cancel_button"><span class="glyphicon glyphicon-remove"></span> Cancel</button>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:3000');
var user1 = user.username;
socket.emit('new_user',user1);
</script>
NB:I got the username on the navbar but I don't get it on the server console.
Ejs render all template variables in server and then return plain html to the client , so
Inside your script , do you have variable global user initialized? :
var user1 = user.username // var user = {username:"foo":} ,something like that before.
If you trying to get user from template variable you could try:
var user1= "<%= user.username%>";
This will render <%= user.username%> inside script tag before send to the client ( browser)

Resources