No data send with socket.io - node.js

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)

Related

How can I send my non-input ejs to MongoDB Atlas

Here is my app.js
const express = require('express');
const https = require('https');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
mongoose.connect("mongodb+srv://Tibor:asdfsadf#weatherdb.pcmad.mongodb.net/weatherDB")
//Adatszerkezet (schema) Mongo-hoz
const weatherSchema = {
varos: String,
lat: Number,
lon: Number,
homerseklet: Number,
meresideje: Date,
szelirany: Number,
szelsebesseg: Number,
legnyomashPa: Number,
legnyomashgmm: Number,
paratartalom: Number,
felhozet: Number
}
//model
const Weather = mongoose.model("Weather", weatherSchema)
const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));
app.get('/', (req, res) => {
//res.send('express működik')
res.render('index', {data: ''});
})
//API elérése(éss mongoDB Post)
app.post('/', (req, res) => {
const location = req.body.location ? req.body.location : "Budapest";
const appId = "asdfasdfasd";
const url = "https://api.openweathermap.org/data/2.5/weather?q=" + location + "&appid=" + appId + "&units=metric";
https.get(url, (response) => {
if (response.statusCode === 200) {
response.on("data", (data) => {
const weatherData = JSON.parse(data);
res.render('index', {data: weatherData});
})
} else {
res.render('index', {data: "0"});
}
});
let newWeather = new Weather({
varos: req.body.varos,
lat: req.body.lat,
lon: req.body.lon,
homerseklet: req.body.homerseklet,
meresideje: req.body.homerseklet,
szelirany: req.body.szelirany,
szelsebesseg: req.body.szelsebesseg,
legnyomashPa: req.body.legnyomashPa,
legnyomashgmm: req.body.legnyomashgmm,
paratartalom: req.body.paratartalom,
felhozet: req.body.felhozet
})
newWeather.save();
});
app.listen(process.env.PORT || 3000, function(){
console.log('A szerver fut/Port:3000');
});
And here is my index.ejs.
<!DOCTYPE html>
<html lang="hu">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WeatherApp</title>
<link rel="stylesheet" href="/public/style.css">
<!-- Bootstrap -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
</head>
<body>
<!-- Már régóta ki akartam próbálni az EJS-t és úgy gondoltam ez egy jó alkalom rá. -->
<!-- Ha talált adatot -->
<% if (data === '') { %>
<div class="container mt-4 col-lg-5">
<!-- Title -->
<h4 class="font-weight-bold">Melyik város időjárását szeretnéd megtekinteni?</h4>
<!-- Város gombok -->
<form action="/" method="post">
<div class="form-group mt-3">
<button type="submit" class="btn btn-primary btn-lg btn-block" name="location" value="Budapest">Budapest</button>
<button type="submit" class="btn btn-primary btn-lg btn-block" name="location" value="Győr">Győr</button>
<button type="submit" class="btn btn-primary btn-lg btn-block" name="location" value="Debrecen">Debrecen</button>
<button type="submit" class="btn btn-primary btn-lg btn-block" name="location" value="Miskolc">Miskolc</button>
<button type="submit" class="btn btn-primary btn-lg btn-block" name="location" value="Pécs">Pécs</button>
<button type="submit" class="btn btn-primary btn-lg btn-block" name="location" value="Sopron">Sopron</button>
<button type="submit" class="btn btn-primary btn-lg btn-block" name="location" value="Szeged">Szeged</button>
<button type="submit" class="btn btn-primary btn-lg btn-block" name="location" value="Gyékényes">Gyékényes</button>
</div>
</form>
<% } else { %>
<div class="container mt-3 ">
<!-- Időjárás szerkezet -->
<div class="card">
<div class="card-body">
<!-- "head" -->
<h5 class="card-title" name="varos"><%= data.name %></h5>
<h8><%= data.sys.country %></h8>
<div class="container">
<p class="text-muted" name="lat"><%= data.coord.lat %></p>
<p class="text-muted" name="lon"><%= data.coord.lon %></p>
</div>
<!-- icon -->
<img class="float-right" src="http://openweathermap.org/img/wn/<%= data.weather[0].icon %>#2x.png" alt="icon">
<!-- Hőmérséklet -->
<p class="display-1" name="homerseklet"><%= data.main.temp%><sup>o</sup>C</p>
<!-- Hőérzet -->
<span class="text-muted">Hőérzet: <%= data.main.feels_like %><sup>o</sup>C</span>
<!-- Az adatok mérésének időpontja -->
<h5 class="font-weight-bold">Mérés időpontja:</h5>
<h6 name="meresideje"><%= new Date(data.dt*1000) %></h6>
<!-- Másodlagos adatok -->
<div class="container mt-3 text-center ">
<div class="row font-weight-bold border-top border-info">
<div class="col border-right border-info"><i class="fas fa-paper-plane"></i> Szélirány</div>
<div class="col"></div>
<div name="szelirany" class="col"><%= data.wind.deg %>°</div>
</div>
<div class="row font-weight-bold">
<div class="col border-right border-info"><i class="fas fa-wind"></i> Szélsebesség</div>
<div class="col"></div>
<div name="szelsebesseg" class="col"><%= data.wind.speed %>m/s</div>
</div>
<div class="row font-weight-bold">
<div class="col border-right border-info"><i class="fas fa-spinner"></i> Légnyomás</div>
<div name="legnyomashPa" class="col"><%= data.main.pressure %>(hPa)</div>
<div name="legnyomashgmm" class="col"><%= data.main.pressure * 0.75 %>(hgmm)</div>
</div>
<div class="row font-weight-bold">
<div class="col border-right border-info"><i class="fas fa-water"></i> Páratartalom</div>
<div class="col"></div>
<div name="paratartalom" class="col"><%= data.main.humidity %>%</div>
</div>
<div class="row font-weight-bold">
<div class="col border-right border-info"><i class="fas fa-eye"></i> Látási-viszonyok</div>
<div class="col"></div>
<div class="col"><%= data.visibility/1000 %>km</div>
</div>
<div class="row font-weight-bold">
<div class="col border-right border-info"><i class="fas fa-cloud"></i> Felhőzet</div>
<div class="col"></div>
<div name="felhozet" class="col"><%= data.clouds.all %>%</div>
</div>
</div>
</div>
</div>
<!-- Másik város gomb(to /) -->
<div class="text-center">
Másik Település
</div>
</div>
<!-- ejs end -->
<% } %>
<script src="https://kit.fontawesome.com/ad862d8e11.js" crossorigin="anonymous">
</script>
</body>
</html>
So this is it.
Somewhy if I check MongoDB I only see empty objects with only an id, maybe I didn't submit it or my ejs is wrong? (I'm new to this)
Also if anyone knows how I can do something like, checking if since the previous date 10 minutes didn't pass then use those measurements?
Any help is welcome!
mongoose.connect('mongodb://localhost:27017/test');
const Cat = mongoose.model('Cat', { name: String });
const kitty = new Cat({ name: 'Zildjian' });
kitty.save().then(() => console.log('meow'));```
```.save()``` is returns a promise resolves with ```(err)```
check that

how can i send data without reloading form node js and ejs

there. I am creating a blog website and I want to post some comments on that post. but the form is reloading am not getting data to store MongoDB. I search on the internet so I got ajax but ajax is not working and this is new for me. help me out with this problem. I am using node js and ejs templating and MongoDB.
node js code
app.post("/do-comment", async (req,res) =>{
const comment = new Comment({name:req.body.name,comment:req.body.comment});
await comment.save();
await Blog.findOneAndUpdate({_id:req.body._id}, {$push: {comment}});
res.send("Comment was added successfully");
})
HTML code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Blogs</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<!-- JavaScript Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-primary">
<div class="container-fluid">
<a class="navbar-brand" href="#">Blogs</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo02" aria-controls="navbarTogglerDemo02" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarTogglerDemo02">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/compose">compose</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>
</li>
</ul>
<form class="d-flex">
<input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
</div>
</div>
</nav>
<div class="container">
<div class="col">
<img src="data:image/<%=post.image.contentType%>;base64,
<%=post.image.data.toString('base64')%>" alt="photo"width="1000px" height="500px" alt="photu">
<h1><%= post.title %></h1>
<p><%= post.content %></p>
</div>
<div class=''>
// form is here for comment
<form method="POST" onsubmit="return doComment(this);" class="theme-form-one">
<input type="hidden" name="_id" value="<%=post._id %>">
<div class="row">
<div class="col-md-6 col-12"><input type="text" name="name" placeholder="Name"></div>
<div class="col-12"><textarea name="comment" placeholder="Comments"></textarea></div>
</div>
<button class="theme-button-one">POST COMMENT</button>
</form>
</div>
//// catching comments here
<div class="">
<div class="container-fluid">
<% data.forEach(function(cData){ %>
<h1><%= cData.name %></h1>
<p><%= cData.comment %></p>
<% }) %>
</div>
</div>
</div>
//js code here
<script>
function doComment(form){
$.ajax({
url:"/post/do-comment",
method:"POST",
data:{name:form.name.value,comment:form.comment.value,
_id:form._id.value},
success: function(response){
alert(response);
}
});
return false;
}
</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?

Resources