How to make my update button work correctly - node.js

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>

Related

How to send embed generated qr-code in ejs using mailgun in node js?

This the code of sending an email using mailgun:
const qrcodeEmail = async (email, subject,text,qrcode,user,data) => {
try {
const requiredPath = path.join(__dirname, "../views/emailTemplates/qrcodeEmail.ejs");
const emailData = await ejs.renderFile(requiredPath,{user:user,data:data,qrcode:qrcode});
var mailData = {
from: 'moilasurprise7#gmail.com',
to: 'moilasurprise7#gmail.com',
subject:subject,
html:emailData,
};
mailgun.messages().send(mailData, function (error, body) {
if(error){
console.log(error);
}
console.log("email sent successfully");
});
} catch (error) {
console.log(error.message);
}
};
The email is sent,the user and order details are showing but the qr-code is not displaying down here is the ejs email template.
Note: the qr-code is generated in this manner.
await QRCode.toDataURL(text);
This is the ejs template where the qrcode is rendered:
<table style="width:100%;max-width:620px;margin:0 auto;background-color:#ffffff;">
<tbody>
<tr>
<td style="padding: 30px 30px 20px">
<p style="margin-bottom: 10px;">Hi <%= user.name %> <%=user.lastName%> ,</p>
<p style="margin-bottom: 10px;">Here is your ticket order</p>
<p style="margin-bottom: 10px;">eventName : <%= data.eventName %> </p>
<p style="margin-bottom: 10px;">EventVenue : <%= data.eventVenue %> </p>
<p style="margin-bottom: 10px;">eventDuration : <%= data.eventDuration %> </p>
<p style="margin-bottom: 10px;">eventRegion : <%= data.eventRegion %> </p>
<p style="margin-bottom: 10px;">Ticket Type : <%= data.category %> </p>
<p style="margin-bottom: 10px;">Ticket price : $<%= data.price %> </p>
<p style="margin-bottom: 10px;">eventDate: <%= data.eventDate.getDate()%>/<%= data.eventDate.getMonth() + 1%>/<%= data.eventDate.getFullYear()%> </p>
<img src="<%=qrcode%>" alt="qr-code">
</td>
</tr>
</tbody>
</table>

Updata table html EJS + Nodejs + Expressjs

I have an application nodejs + expressjs + ejs.
I am building a history search screen, my question is how to update my ejs html table with the values ​​returned in the response.
Uploading the screen with the values ​​is working, but when I enter the filters and search, I would like to update my table.
In the example below is how to use to load the html the first time with the data of the query, I would like to fill in an initial and final date and click on searching and updating the html.
EJS HTML
<div class="row">
<div class="col-md-2">
<div class="form-group">
<label for="dataPrimayID">Date Primary</label>
<input type="text" class="form-control datepickerDefault" id="dataPrimayID" name="dataPrimary" maxlength="250">
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label for="dataFinalID">Date Final</label>
<input type="text" class="form-control datepickerDefault" id="dataFinalID" name="dataFinal" maxlength="250">
</div>
</div>
<div class="col-md-2">
<a id="btnSearch" class="btn btn-primary">Search</a>
</div>
</div>
<div class="row">
<div class="table-responsive col-md-12">
<table id="dataTableHistoricoID" class="table table-striped" cellspacing="0" cellpadding="0">
<thead>
<tr>
<th>Name</th>
<th>LastName</th>
</tr>
</thead>
<tbody>
<% if(data.length > 0){ %>
<% for ( var i = 0 ; i < data.length ; i++){ %>
<tr>
<td>
<%= data[i].name%>
</td>
<td>
<%= data[i].lastname%>
</td>
</tr>
<% } %>
<% } %>
</tbody>
</table>
</div>
</div>
ROUTER
var express = require('express');
var router = express.Router();
var historyController = require('../controllers/history-controller');
router.get('/find', historyController.findHistory);
module.exports = router;
Controller
db.query(sql, function (err, rows) {
if (err) {
var message = err.message;
console.log(message);
return res.status(500).send(message);
}else {
var data = rows;
res.render('history/search-history', {data: data});
}
});
EJS is static after compiling, you can't change it on backend-side. There are two ways of it.
Refreshing the page every time you want to render new content.
Implement client-side JS code that will handle api requests and render new elements.
For example, using Jquery:
$.post(url, (result) => {
let data = JSON.parse(result);
let innerHTML = '';
for (let item of data) {
innerHTML += `<tr>
<td>
${item.name}
</td>
<td>
${item.lastname}
</td>
</tr>`;
}
$('#dataTableHistoricoID tbody').html(innerHTML)
};

How does routing affect form validation

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

Saving sorted order to mongo using ui-sortable

I'm currently teaching myself the ins and outs of building a MEAN app. I started with the basic todo app and modified it pretty heavily to support multiple key value pairs and have updated the UI using bootstrap.
It's currently hosted here: http://surveymanager-30817.onmodulus.net/
I've implemented ui-sortable, and it works perfectly by itself.
The challenge I'm having, that I cannot seem to find any relevant documentation or tutorials for - is how to communicate the updated sort order to mongo so when I refresh the page, ng-repeat will repeat question in questions with the order that I had previously created.
Here is the HTML
<!-- index.html -->
<!doctype html>
<!-- ASSIGN OUR ANGULAR MODULE -->
<html ng-app="QuestionManager">
<head>
<!-- META -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"><!-- Optimize mobile viewport -->
<title>Question Manager</title>
<!-- SCROLLS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/question-bootstrap.css" rel="stylesheet">
<style>
html { overflow-y:scroll; }
body { padding-top:30px; }
#todo-list { margin-bottom:30px; }
</style>
<!-- SPELLS -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script><!-- load jquery -->
<script src="//code.jquery.com/ui/1.9.1/jquery-ui.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script><!-- load angular -->
<script src="js/sortable.js"></script>
<script src="core.js"></script>
</head>
<!-- SET THE CONTROLLER AND GET ALL TODOS -->
<body ng-controller="mainController">
<div class="container sm_head">
<div class="col-sm-6">
</div>
<div class="col-sm-6">
<h2 class="pull-right">Survey Manager</h2>
</div>
</div>
<div class="container">
<!-- Nav tabs -->
<ul id="navtabs" class="nav nav-tabs" role="tablist">
<li class="active">Manage</li>
<li>Create</li>
<li>Render Code</li>
<li>About</li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<div class="tab-pane active" id="manage">
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-heading">Manage Question Order<span class="badge pull-right">{{ questions.length }} Questions</span></div>
<!-- Table -->
<table class="table">
<thead>
<tr>
<th>Order</th>
<th>Question Name</th>
<th>Evergage Field</th>
<th>Username</th>
<th>Options</th>
</tr>
</thead>
<tbody ui-sortable="sortableOptions" ng-model="questions">
<tr ng-repeat="question in questions">
<td>{{ question.order }}</td>
<td>{{ question.meanName }}</td>
<td>{{ question.fieldName }}</td>
<td>#mdo</td>
<td>
<button type="button" class="btn btn-default btn-sm" ng-click="deleteQuestion(question._id)">
<span class="ques-list glyphicon glyphicon-remove"></span> delete </button>
</td>
</tr>
</tbody>
</table>
</div>
<div class="col-md-8">
<form class="form-horizontal">
<fieldset>
<!-- Form Name -->
<legend>Question Details</legend>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="Question Name">Question Order</label>
<div class="col-md-8">
<input id="Question Order" name="Question Order" type="text" placeholder="Question Order" class="form-control input-md" ng-model="formData.order">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="Question Name">Question Name</label>
<div class="col-md-8">
<input id="Question Name" name="Question Name" type="text" placeholder="Write something meaningful" class="form-control input-md" ng-model="formData.meanName">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="Custom Field Name">Custom Field</label>
<div class="col-md-8">
<input id="Custom Field Name" name="Custom Field Name" type="text" placeholder="Format: User.Profile.xx.xx.xx ( 1 or 3 additional words)" class="form-control input-md" ng-model="formData.fieldName">
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="Create"></label>
<div class="col-md-4">
<button id="Create" name="Create" class="btn btn-primary" ng-click="createQuestion()">Create</button>
</div>
</div>
</fieldset>
</form>
</div>
</div>
<div class="tab-pane" id="create">
</div>
<div class="tab-pane" id="render">...</div>
<div class="tab-pane" id="about">...</div>
</div>
</div>
<script src="js/bootstrap.min.js"></script>
</body>
</html>
Here is the client side:
// public/core.js
var QuestionManager = angular.module('QuestionManager', ['ui.sortable']);
function mainController($scope, $http) {
$scope.formData = {};
// when landing on the page, get all questions and show them
$http.get('/api/questions')
.success(function(data) {
$scope.questions = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
// when submitting the add form, send the text to the node API
$scope.createQuestion = function() {
$http.post('/api/questions', $scope.formData)
.success(function(data) {
$scope.formData = {};
console.log('fuck you!');
$scope.questions = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
};
// delete a question after checking it
$scope.deleteQuestion = function(id) {
$http.delete('/api/questions/' + id)
.success(function(data) {
$scope.questions = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
};
$scope.$watch("questions", function(newVal, oldVal) {
console.log("oldval", oldVal);
console.log("newVal", newVal);
});
$scope.sortableOptions = {
update: function(e, ui) {
$http.put('/api/questions', $scope.questions)
console.log($scope.questions);
},
axis: 'y'
};
}
// Some Bootstrap Initializers
$('#navtabs>li a').click(function (e) {
e.preventDefault()
$(this).tab('show')
})
And here is the server side with my random test and console logs starting at line 44
// server.js
var express = require('express');
var app = express(); // create our app w/ express
var mongoose = require('mongoose'); // mongoose for mongodb
var morgan = require('morgan'); // log requests to the console (express4)
var bodyParser = require('body-parser'); // pull information from HTML POST (express4)
var methodOverride = require('method-override'); // simulate DELETE and PUT (express4)
mongoose.connect('mongodb://ewill3532:12qwaszx#proximus.modulusmongo.net:27017/pUxo2hir'); // connect to mongoDB database locally
app.use(express.static(__dirname + '/public')); // set the static files location /public/img will be /img for users
app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.urlencoded({'extended':'true'})); // parse application/x-www-form-urlencoded
app.use(bodyParser.json()); // parse application/json
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json
app.use(methodOverride());
var question = mongoose.model('question', {
order : String,
fieldName : String,
meanName : String
});
app.get('/api/questions', function(req, res) {
// use mongoose to get all questions in the database
question.find(function(err, questions) {
// if there is an error retrieving, send the error. nothing after res.send(err) will execute
if (err)
res.send(err)
res.json(questions); // return all questions in JSON format
});
});
// create todo and send back all questions after creation
app.post('/api/questions', function(req, res) {
// create a todo, information comes from AJAX request from Angular
question.create({
order : req.body.order,
fieldName : req.body.fieldName,
meanName : req.body.meanName,
done : false
}, function(err, todo) {
if (err)
res.send(err);
// get and return all the questions after you create another
question.find(function(err, questions) {
if (err)
res.send(err)
res.json(questions);
});
});
});
// delete a todo
app.delete('/api/questions/:todo_id', function(req, res) {
question.remove({
_id : req.params.todo_id
}, function(err, todo) {
if (err)
res.send(err);
// get and return all the questions after you create another
question.find(function(err, questions) {
if (err)
res.send(err)
res.json(questions);
});
});
});
// let's just put this here so that it comes back as found
app.put('/api/questions', function(req, res) {
});
app.get('*', function(req, res) {
res.sendfile('./public/index.html'); // load the single view file (angular will handle the page changes on the front-end)
});
// listen (start app with node server.js) ======================================
app.listen(8080);
console.log("App listening on port 8080");
Any help here, or if someone can point me to some good documentation or tutorials - either way would be very helpful!'
Thanks!

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