Crud app API POST error, not able to find the issue - node.js

Making a crud app with Node and Mongo.
While updating a user the API is not able to POST the data and returning an error in the browser Cannot POST /update-user
I am able to add a user, but while updating the user it is returning an error.
This is my Add user page:
<!-- include header -->
<%- include('include/_header') %>
<!-- /include header -->
<!--Main site-->
<main id="site-main">
<div class="container">
<div class="box-nav d-flex justify-between">
<div class="filter">
<i class='fas fa-angle-double-left'></i>All Users
</div>
</div>
<div class="form-title text-center">
<h2 class='text-dark'>New User</h2>
<span class='text-light'>Use the form below to create a new account</span>
</div>
<!-- add user form -->
<%- include('include/_form') %>
</div>
</main>
<!--Main site-->
<!-- include footer -->
<%- include('include/_footer') %>
<!-- /include footer -->
This is the footer:
<script src="<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="../../assets/js/index.js"></script>
</body>
</html>
This is the Index.js connected to the footerL:
$("#add_user").submit(function(event){
alert("Data inserted successfully");
})
$("#update_user").submit(function(event){
event.preventDefault();
var unindexed_array = $(this).serializeArray();
var data = {}
$.map(unindexed_array, function(n, i){
data[n['name']] = n['value']
})
})
This is the index.js connected to the footer:
$("#add_user").submit(function(event){
alert("Data inserted successfully");
})
$("#update_user").submit(function(event){
event.preventDefault();
var unindexed_array = $(this).serializeArray();
var data = {}
$.map(unindexed_array, function(n, i){
data[n['name']] = n['value']
})
})
This is the Update user form:
<!-- include header -->
<%- include('include/_header') %>
<!-- /include header -->
<!-- Main Site -->
<main id="site-main">
<div class="container">
<div class="box-nav d-flex justify-between">
<div class="filter">
<i class="fas fa-angle-double-left"></i> All Users
</div>
</div>
<div class="form-title text-center">
<h2 class="text-dark">Update User</h2>
<span class="text-light">Use the below form to Update an account</span>
</div>
<!-- add user form -->
<!-- form handling -->
<form method="POST" id="update_user">
<div class="new_user">
<div class="form-group">
<label for="name" class="text-light">Name</label>
<input type="hidden" name="id" value="<%= user._id %>">
<input type="text" name="name" value="<%= user.name %>" placeholder="Mark Stoenis">
</div>
<div class="form-group">
<label for="Email" class="text-light">Email</label>
<input type="text" name="email" value="<%= user.email%>" placeholder="example#gmail.com">
</div>
<div class="form-group">
<label for="gender" class="text-light">Gender</label>
<div class="radio inline">
<input type="radio" id="radio-2" name="gender" value="Male" <%= user.gender == 'Male' ? 'checked' : '' %>>
<label for="radio-2" class="radio-label">Male</label>
</div>
<div class="radio inline">
<input type="radio" id="radio-3" name="gender" value="Female" <%= user.gender == 'Female' ? 'checked' : '' %> >
<label for="radio-3" class="radio-label">Female</label>
</div>
</div>
<div class="form-group">
<label for="gender" class="text-light">Status</label>
<div class="radio inline">
<input type="radio" id="radio-4" name="status" value="Active" <%= user.status == 'Active' ? 'checked' : '' %> >
<label for="radio-4" class="radio-label">Active</label>
</div>
<div class="radio inline">
<input type="radio" id="radio-5" name="status" value="Inactive" <%= user.status == 'Inactive' ? 'checked' : '' %> >
<label for="radio-5" class="radio-label">Inactive</label>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn text-dark update">Save</button>
</div>
</div>
</form>
</div>
</main>
<!-- /Main Site -->
<!-- include footer -->
<%- include('include/_footer') %>
<!-- /include footer -->

Related

How to load comments without refreshing the page in nodeJs and Ajax

The actual challenge that I am facing now is how to load the comment properly. My Ajax is creating the comment but I am struggling to load the comment properly in line with other comments.
what happening now is that the comment loads but it doesn't load properly, I am struggling to load it with the right ID in the right place. when it loads, it shows my title and descriptions together and it doesn't load the date.
<div class="container">
<div class="row">
<div class="col-sm-6 col-sm-offset-3">
<h1>Comment App</h1>
<form action="/programs/<%= program._id %>/createComment" method="POST" >
<div class="form-group">
<input name="name" id="username" class="form-control" placeholder="username">
</div>
<div class="form-group">
<textarea name="description" id="descriptioncomment" class="form-control" placeholder="comment"></textarea>
</div>
<div class="form-group">
<input type="submit" id="post-comment" class="btn btn-primary" value="Submit">
</div>
</form>
<ul id="commentList" class="list-group">
</ul>
</div>
</div>
</div>
<section class="content-item" id="comments">
<div class="row" id="comment-lists" >
<div class="col-sm-10" >
<h3 id="comments-count" ><%= program.programcomments.length%> </h3>
<% program.programcomments.forEach(comments=> { %>
<div class="media" >
<div class="media-body" >
<h4 class="media-heading" id="lists" ><%= comments.name %></h4>
<p id="lists" ><%=comments.description %></p>
<ul class="list-unstyled list-inline media-detail pull-left" id="lists">
<li id="lists"><i class="fa fa-calendar" ></i><%= moment(comments.createdAt).format('llll') %></li>
</ul>
</div>
</div>
<% });%>
</div>
</div>
</section>
$('#post-comment').on('click', function(event) {
event.preventDefault();
$.ajax({
url : "/programs/<%= program._id %>/createComment",
method : 'POST',
data : {
name : $('#username').val(),
description : $('#descriptioncomment').val()
},
success : function(result ) {
$('.form-control').each(function () {
let comments = this.value;
$('#comment-lists').append($('#lists').text(comments))
document.getElementById('comments-count').innerHTML++
});
$("#username").val('');
$("textarea#descriptioncomment.form-control").val('');
}
});
})
You are using same ids for mutliple elements so first remove them and use class. Then , you can generate entire media div inside success function of ajax with the value of inputs and then append them inside your comment-lists div.
Demo Code :
$('#post-comment').on('click', function(event) {
event.preventDefault();
/*$.ajax({
url: "/programs/<%= program._id %>/createComment",
method: 'POST',
data: {
name: $('#username').val(),
description: $('#descriptioncomment').val()
},
success: function(result) {*/
//append new div .. with username & desc
$('#comment-lists').append(`<div class="media">
<div class="media-body">
<h4 class="media-heading">${$('#username').val()}</h4>
<p class="lists">${$('#descriptioncomment').val()}</p>
<ul class="list-unstyled list-inline media-detail pull-left lists">
<li><i class="fa fa-calendar"></i>${moment(new Date()).format('llll') }</li>
</ul>
</div>
</div>`)
$("#comments-count").text(parseInt($("#comments-count").text()) + 1) //updated total
//then emtpy
$("#username").val('');
$("textarea#descriptioncomment.form-control").val('');
/*}
});*/
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<div class="container">
<div class="row">
<div class="col-sm-6 col-sm-offset-3">
<h1>Comment App</h1>
<form action="/programs/<%= program._id %>/createComment" method="POST">
<div class="form-group">
<input name="name" id="username" class="form-control" placeholder="username">
</div>
<div class="form-group">
<textarea name="description" id="descriptioncomment" class="form-control" placeholder="comment"></textarea>
</div>
<div class="form-group">
<input type="submit" id="post-comment" class="btn btn-primary" value="Submit">
</div>
</form>
<ul id="commentList" class="list-group">
</ul>
</div>
</div>
</div>
<section class="content-item" id="comments">
<div class="row" id="comment-lists">
<div class="col-sm-10">
<h3 id="comments-count">2</h3>
<div class="media">
<div class="media-body">
<h4 class="media-heading">Abc</h4>
<p class="lists">Descp xyz</p>
<ul class="list-unstyled list-inline media-detail pull-left lists">
<li><i class="fa fa-calendar"></i>23-2-2022</li>
</ul>
</div>
</div>
<div class="media">
<div class="media-body">
<h4 class="media-heading lists">Abc</h4>
<p class="lists">Descp xyz</p>
<ul class="list-unstyled list-inline media-detail pull-left lists">
<li><i class="fa fa-calendar"></i>23-2-2022</li>
</ul>
</div>
</div>
</div>
</div>
</section>

My Bootstrap form completely disappears due to use of If-else statement with EJS

<div class="row" style="margin: auto; max-width: 850;">
<h1 style="text-align: center">User Registration</h1>
<!-- <div class="well well-sm"><strong><span class="glyphicon glyphicon-asterisk" style="color: red"></span>Required Field</strong></div>-->
<form role="form" action="/users/addUser" method="POST">
<div class="form-group">
<div class="span6">
<div class="col-lg-4">
<div class="form-group">
<label for="InputEmail">Username</label>
<div class="input-group">
<input type="text" style="width: 180%" class="form-control" id="username" name="username" placeholder="username" required>
<!--
<span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>
-->
</div>
</div>
</div>
</div>
<div class="span6">
<div class="col-lg-4">
<div class="form-group">
<label for="InputEmail">Password</label>
<div class="input-group">
<input type="password" style="width: 180%" class="form-control" id="password" name="password" placeholder="password" required>
<!--
<span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>
-->
</div>
</div>
</div>
</div>
<!--
<div class="form-group">
<label for="InputMessage">Enter Message</label>
<div class="input-group">
<textarea name="InputMessage" id="InputMessage" class="form-control" rows="5" required></textarea>
<span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>
</div>
</div>
<input type="submit" name="submit" id="submit" value="Submit" class="btn btn-info float-xs-right">-->
<div class="col-lg-5 push-md-1">
<div class="col-md-12">
<% if(isRegistered) { %>
<div class="alert alert-success">
<strong><span class="glyphicon glyphicon-ok"></span> <%= msg %>.</strong>
</div>
<% } else { %>
<div class="alert alert-danger">
<span class="glyphicon glyphicon-remove"></span><strong> <%= msg %> </strong>
</div>
<% } %>
</div>
</div>
<br>
<br>
<br>
<hr>
<input type="submit" name="submit" id="submit" value="Submit" class="btn btn-info float-xs-right">
</form>
</div>
As shown above, if i use "If-else " statement with EJS, my form disappears and if i remove it, my form appears on the browser again.
What i'm trying is to have a registration page where if the user already exists, an alert message to be displayed on the corner side of the browser saying, 'user already exists'. By the way this alert message is coming from my db (Oracle 11g).

Angular 4 email Contact form

I'm pretty new to Angular and have been tasked to complete a "Contact Us" form to allow customers to send emails through the web form.
The HTML:
<div class="content-section">
<div class="container">
<div class="row">
<div class="">
<h2 class="intro-title">Contact Us</h2>
<form class="well form-horizontal" action=" " method="post" id="contact_form">
<div class="col-lg-6 spacer">
<div class="fadeIn-1">
<p>
<strong>Contact us</strong>
<br />
111.222.3333
<br />
information#mysite.com
</p>
</div>
<br />
<div class="fadeIn-2">
<p>
<strong>Office 1</strong>
<br />
Our street address
<br />
City, state, zip
</p>
</div>
<br />
<div class="fadeIn-3">
<p>
<strong>Office 2</strong>
<br />
street address
<br />
City, state, zip
</p>
</div>
</div>
<fieldset>
<!-- Form Name -->
<legend>Send us a message</legend>
<!-- Text input-->
<div class="form-group">
<!--<label class="col-md-4 control-label">First Name</label>-->
<div class="col-md-6 inputGroupContainer">
<div class="input-group animated-delay-1">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input name="name" placeholder="Name" class="form-control" type="text">
</div>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<!--<label class="col-md-4 control-label">E-Mail</label>-->
<div class="col-md-6 inputGroupContainer">
<div class="input-group animated-delay-2">
<span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span>
<input name="email" placeholder="E-Mail Address" class="form-control" type="text">
</div>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<!--<label class="col-md-4 control-label">Phone #</label>-->
<div class="col-md-6 inputGroupContainer">
<div class="input-group animated-delay-3">
<span class="input-group-addon"><i class="glyphicon glyphicon-earphone"></i></span>
<input name="phone" placeholder="(801)222-3333" class="form-control" type="text">
</div>
</div>
</div>
<div class="form-group">
<!--<label class="col-md-4 control-label">Subject</label>-->
<div class="col-md-6 inputGroupContainer">
<div class="input-group animated-delay-4">
<span class="input-group-addon"><i class="glyphicon glyphicon-bookmark"></i></span>
<input name="subject" placeholder="Subject" class="form-control" type="text">
</div>
</div>
</div>
<div class="form-group">
<!--<label class="col-md-4 control-label">Message</label>-->
<div class="col-md-6 inputGroupContainer">
<div class="input-group animated-delay-5">
<span class="input-group-addon"><i class="glyphicon glyphicon-pencil"></i></span>
<textarea rows="9" class="form-control" name="comment" placeholder="Message">
</textarea>
</div>
</div>
</div>
<!-- Button -->
<div class="form-group">
<div class="col-md-4">
<button type="submit" class="btn btn-primary">Send
<span class="glyphicon glyphicon-send"></span>
</button>
</div>
</div>
</fieldset>
</form>
</div>
</div>
</div>
</div>
This is this the component:
import { Component } from '#angular/core';
import { trigger, state, style, transition, animate } from '#angular/animations';
import { slideInOutAnimation, fadeInAnimation } from '../_animations/index';
#Component({
selector: 'contact-page',
templateUrl: './contact.component.html',
styleUrls: ['./contact.component.css'],
animations: [slideInOutAnimation, fadeInAnimation, trigger('slideInOut', [
state('in', style({
transform: 'translate3d(0, 0, 0)'
})),
state('out', style({
transform: 'translate3d(100%, 0, 0)'
})),
transition('in => out', animate('400ms ease-in-out')),
transition('out => in', animate('400ms ease-in-out'))
]),
],
host: {
'(window:scroll)': 'updateHeader($event)',
'[#slideInOutAnimation]': '',
'[#fadeInAnimation]': ''
}
})
export class ContactComponent {
title = 'app';
isScrolled = false;
currPos: Number = 0;
startPos: Number = 0;
changePos: Number = 0;
menuState = 'out';
constructor() { }
updateHeader(evt) {
this.currPos = (window.pageYOffset || evt.target.scrollTop) - (evt.target.clientTop || 0);
if (this.currPos >= this.changePos) {
this.isScrolled = true;
} else {
this.isScrolled = false;
}
}
}
I've looked at options such as "nodemailer" and I just can't seem to figure out how it all works.
I need the email to be sent to our email address when a customer clicks the submit button. Any suggestions?
Also, I'm not really sure what else is needed to get help, so if you need anything else, I am happy to post it up.

Views not refreshing correctly using SailsJS

in my code, i have a view called "show.ejs" which shows client details. the proble; now is that if i update client details (image, associated docs, ...) the content remains the same and changes only if i refresh the page ( by F5 ) .
this my update and show actions in ClientController :
findOne : function(req,res){
Client.findOne({
id : req.param('id')
})
.populate('docs')
.populate('sites')
.exec(function(err,client){
if(err) throw err;
if(client) {
return res.view('client/show', {
client : client
});
} else {
return res.redirect('/client');
}
})
},
update : function(req,res){
var name = req.param('name'),
id = req.param('id'),
town = req.param('town'),
adress = req.param('adress'),
postalCode = req.param('postalCode'),
telephone = req.param('telephone'),
email = req.param('email'),
fax = req.param('fax'),
responsable = req.param('responsable'),
website = req.param('website'),
activity = req.param('activity');
Client.findOne({id : id}).exec(function(err,client) {
if(err) console.log(err);
client.name = name;
client.town = town;
client.adress = adress;
client.telephone = telephone;
client.fax = fax;
client.website = website;
client.email=email;
client.responsable=responsable;
client.postalCode=postalCode;
client.activity = activity;
client.save();
req.file('logo').upload({
dirname: require('path')
.resolve(sails.config.appPath+'/assets/uploads/clients/logos/')
}, function (err, logo) {
if (err) throw err;
if(typeof logo !== 'undefined' && logo.length > 0 ) {
require('fs').unlink('./assets/uploads/clients/logos/'+client.logo, function(err){
if(err) console.log(err)
client.logo = require('path').basename(logo[0].fd);
client.save();
})
}
return res.redirect('/client/'+client.id );
});
})
}
and this is how i setup the view :
<div class="row">
<div class="col-md-12">
<!-- BEGIN PROFILE SIDEBAR -->
<div class="profile-sidebar" style="background-color: #f5f5f5;">
<!-- PORTLET MAIN -->
<div class="portlet light profile-sidebar-portlet " style="background-color: #f5f5f5;">
<!-- SIDEBAR USERPIC -->
<div class="profile-userpic">
<img src="/uploads/clients/logos/<%= client.logo %>" class="img-responsive img-circle" alt="image client"> </div>
<!-- END SIDEBAR USERPIC -->
<!-- SIDEBAR USER TITLE -->
<div class="profile-usertitle ">
<div class="profile-usertitle-name"><%= client.name %></div>
<div class="profile-usertitle-job"> Client </div>
</div>
</div>
<!-- END PORTLET MAIN -->
<!-- PORTLET MAIN -->
<div class="portlet light " style="background-color: #f5f5f5;">
<!-- STAT -->
<div class="row list-separated profile-stat">
<div class="col-md-6 col-sm-6 col-xs-6">
<div class="uppercase profile-stat-title"> <%= 44 %> </div>
<div class="uppercase profile-stat-text"> Sites </div>
</div>
<div class="col-md-6 col-sm-6 col-xs-6">
<div class="uppercase profile-stat-title"><%= 49 %> </div>
<div class="uppercase profile-stat-text"> Documents </div>
</div>
</div>
<!-- END STAT -->
<div>
<div class="margin-top-20 profile-desc-link">
<i class="fa fa-map-marker"></i>
<span class="profile-desc-text" ><%= client.adress %></span>
</div>
<div class="margin-top-20 profile-desc-link">
<i class="fa fa-envelope"></i>
<%= client.email %>
</div>
<div class="margin-top-20 profile-desc-link">
<i class="fa fa-globe"></i>
<%= client.website %>
</div>
</div>
</div>
<!-- END PORTLET MAIN -->
</div>
<!-- END BEGIN PROFILE SIDEBAR -->
<!-- BEGIN PROFILE CONTENT -->
<div class="profile-content">
<div class="row">
<div class="col-md-12">
<div class="portlet light ">
<div class="portlet-title tabbable-line">
<div class="caption caption-md">
<i class="icon-globe theme-font hide"></i>
<span class="caption-subject font-blue-madison bold uppercase">Client N° <strong> <%= client.id %></strong></span>
</div>
<ul class="nav nav-tabs">
<li class="active">
informations
</li>
<li>
Documents
</li>
<li>
Sites
</li>
</ul>
</div>
<div class="portlet-body">
<div class="tab-content">
<!-- PERSONAL INFO TAB -->
<div class="tab-pane active" id="tab_1_1">
<form class="form-horizontal" role="form" action="edit">
<div class="form-actions">
<div class="row">
<div class="col-md-12">
<div class="row">
<div class="col-md-offset-10 col-md-2">
<input type="text" hidden name="id" value="<%=client.id%>">
<button type="submit" class="btn green">
<i class="fa fa-pencil"></i> Modifier</button>
</div>
</div>
</div>
</div>
</div>
<div class="form-body">
<h3 class="form-section">Informations Personneles </h3>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-4">ID :</label>
<div class="col-md-8">
<strong> <p class="form-control-static"> <%= client.id %> </p></strong>
</div>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-4">Nom :</label>
<div class="col-md-8">
<strong> <p class="form-control-static"> <%= client.name %> </p></strong> </strong>
</div>
</div>
</div>
<!--/span-->
</div>
<!--/row-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-4">Responsable :</label>
<div class="col-md-8">
<strong> <p class="form-control-static"><%= client.responsable %></p></strong>
</div>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-4">Email :</label>
<div class="col-md-8">
<strong> <p class="form-control-static"> <%= client.email %> </p></strong>
</div>
</div>
</div>
<!--/span-->
</div>
<!--/row-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-4">Téléphone :</label>
<div class="col-md-8">
<strong> <p class="form-control-static"> <%= client.telephone %> </p></strong>
</div>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-4">Fax :</label>
<div class="col-md-8">
<strong> <p class="form-control-static"> <%= client.fax %> </p></strong>
</div>
</div>
</div>
<!--/span-->
</div>
<!--/row-->
<h3 class="form-section">Adresse</h3>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label col-md-3">#</label>
<div class="col-md-9">
<strong> <p class="form-control-static"> <%= client.adress %> </p></strong>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-4">Ville:</label>
<div class="col-md-8">
<strong> <p class="form-control-static"> <%= client.town %> </p></strong>
</div>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-6">Code postal:</label>
<div class="col-md-6">
<strong> <p class="form-control-static"> <%= client.postalCode %></p></strong>
</div>
</div>
</div>
<!--/span-->
</div>
<!--/row-->
</div>
</form>
</div>
<!-- END PERSONAL INFO TAB -->
<!-- CHANGE AVATAR TAB -->
<div class="tab-pane" id="tab_1_2">
<div class="form-actions">
<div class="row">
<div class="col-md-12">
<div class="row">
<div class="col-md-offset-9 col-md-3">
<button type="submit" class="btn green" data-toggle="modal" href="#basic">
<i class="fa fa-plus"></i> Ajouter un doc </button>
</div>
</div>
</div>
</div>
</div>
<!--- doc model -->
<div class="modal fade" id="basic" tabindex="-1" role="basic" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h4 class="modal-title">Ajouter un Document</h4>
</div>
<div class="modal-body">
<form action="/client/addDocument" method="POST" enctype="multipart/form-data">
<input type="text" hidden name="id" value="<%= client.id %>">
<div class="form-group" style="padding-bottom: 22px;">
<label class="col-md-3 control-label">Titre</label>
<div class="col-md-9">
<div class="input-group">
<span class="input-group-addon input-circle-left">
<i class="fa fa-info-circle"></i>
</span>
<input type="text" class="form-control input-circle-right" placeholder="titre du document" name="title"> </div>
</div>
</div>
<br>
<div class="form-group" style="padding-bottom: 22px;">
<label class="col-md-3 control-label">Description</label>
<div class="col-md-9">
<div class="input-group">
<span class="input-group-addon input-circle-left">
<i class="fa fa-info-circle"></i>
</span>
<textarea type="text" class="form-control input-circle-right" name="description" placeholder="description du document"> </textarea>
</div>
</div>
</div>
<div class="form-group" style="padding-bottom: 22px; padding-top: 40px;">
<label class="col-md-3 control-label">Document</label>
<div class="col-md-9">
<div class="input-group">
<div class="fileinput fileinput-new" data-provides="fileinput">
<span class="btn green btn-file">
<span class="fileinput-new"> Selectionner Fichier </span>
<span class="fileinput-exists"> Changer </span>
<input type="file" name="fichier"> </span>
<span class="fileinput-filename"> </span>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn dark btn-outline" data-dismiss="modal">Fermer</button>
<button type="submit" class="btn green">Enregistrer</button>
</form>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- fin doc model -->
<br>
<div class="portlet light bordered">
<div class="portlet-title">
<div class="caption font-green">
<i class=" fa fa-file font-green"></i>
<span class="caption-subject bold uppercase" style="margin-right : 11px;">Liste des Documents</span>
</div>
</div>
<div class="portlet-body">
<table class="table table-striped table-bordered table-hover dt-responsive" width="100%" id="sample_1">
<thead>
<tr>
<th class="all">#</th>
<th class="min-tablet">Titre</th>
<th class="desktop">Description</th>
<th class="all" style="width : 66px">Action.</th>
</tr>
</thead>
<tbody>
<% _.each(client.docs, function (doc) { %>
<tr>
<td ><%=doc.id%></td>
<td ><%= doc.title %></td>
<td ><%= doc.description %></td>
<center> <td>
<a href="#" title="telecharger" class="btn btn-circle btn-icon-only green" ><i class="fa fa-download" ></i></a>
<a href="#" title="Supprimer" class="btn btn-circle btn-icon-only purple-sharp" data-toggle="confirmation" data-placement="left" data-btn-ok-label="Continuer" data-btn-ok-icon="icon-like" data-btn-ok-class="btn-success" data-btn-cancel-label="Annuler!"
data-btn-cancel-icon="icon-close" data-btn-cancel-class="btn-danger"><i class="fa fa-trash-o"></i></a>
</td></center>
</tr>
<% }) %>
</tbody>
</table>
</div>
</div>
</div>
Actually following your code, the problems reside in
client.save()
which is an asynchronous function.
the problem is you are changing the client and you are not waiting for the changes to be saved to upload the logo and reload the data.
here's the official doc, which is stating that model.save has a callback to it.
client.save(function(){
/*your code */
})
The view, with those EJS functions is doing what is expected to do. You see, you are not providing some way to magically change data on-the-fly. Instead what EJS and your controller is doing is this: Get all data needed - with findOne -> Put that data on the view - with EJS and <% %> markers -> Render and serve a static HTML document - res.view.
If you need data to change on the fly you need a more powerful framework on the frontend, like Vuejs or Angular... EJS is meant to assembly a static page with dynamic data ONCE. Take a look at the docs

How to show error message on each input type field in nodejs using express-validator

I am begginer in nodejs and I am using express-validator library to validate form.
I want to display error message seprately to each input type field,
not group wise.
Currently my code shows the error in group like
Name is required!
Email is required!
Email is wrong!
Mobile is required!
========================================================================
Controller Code
employeeController.saveEmployee = function(req,res){
var employeeData = req.body;
// Start Validation
req.checkBody('employeeName','Name is required!').notEmpty();
req.checkBody('employeeEmail','Email is required!').notEmpty();
req.checkBody('employeeEmail','Email is wrong!').isEmail();
req.checkBody('employeeMobile','Mobile is required!').notEmpty();
req.sanitize('employeeName').trim();
req.sanitize('employeeName').escape();
// End Validation
var errors = req.validationErrors();
console.log(errors);
if(!errors){
var employee = new Employee({
name : req.body.employeeName,
email : req.body.employeeEmail,
mobile : req.body.employeemobile,
});
employee.save(function(err){
if(err){
throw err;
}
console.log('User inserted successfully');
res.redirect('/employee-list');
});
}else{
console.log(employeeData.employeeName);
res.render('employee/add-employee',{
errors : errors,
employeeData : employeeData
});
}
};
View template
<div class="col-md-12">
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Add Employee Profile</h3>
<h5 class='text-aqua pull-right' style='margin-top: 0px;'>
<i class="fa fa-backward"></i> Back
</h5>
</div>
<p>
<% if(errors){ %>
<ul>
<% for(var i = 0; i < errors.length; i++){ %>
<li> <%= errors[i].msg %> </li>
<% } %>
</ul>
<% } %>
</p>
<!-- form start -->
<form method = 'post' action = '/save-employee'>
<div class="box-body">
<div class="form-group col-md-4">
<label>Name</label>
<div class='input-group'>
<span class="input-group-addon"><i class="fa fa-pencil"></i></span>
<input type='text' name='employeeName' id='employeeName' value='<%= employeeData.employeeName %>' class='form-control' placeholder='Employee Name'>
</div>
</div>
<div class="form-group col-md-4">
<label>Email</label>
<div class='input-group'>
<span class="input-group-addon"><i class="fa fa-pencil"></i></span>
<input type='text' name='employeeEmail' id='employeeEmail' value='<%= employeeData.employeeEmail %>' class='form-control' placeholder='Employee Email'>
</div>
</div>
<div class="form-group col-md-4">
<label>Mobile</label>
<div class='input-group'>
<span class="input-group-addon"><i class="fa fa-pencil"></i></span>
<input type='text' name='employeeMobile' id='employeeMobile' value='<%= employeeData.employeeMobile %>' class='form-control' placeholder='Employee Mobile'>
</div>
</div>
</div>
<div class="callout" id='message-container' style='display:none;'></div>
<div class="box-footer">
<button type='submit' name='saveEmployeeProfile' class='btn btn-primary'>Save</button>
</div>
</form>
</div>
</div>
Ok, so what you have to do - is separate errors.
Your controller file:
employeeController.saveEmployee = function(req,res){
const nameRequired = 'Name is required!';
const emailRequired = 'Email is required!';
const emailNotValid = 'Email is wrong!';
const mobileRequired = 'Mobile is required!';
const employeeData = req.body;
// Start Validation
req.checkBody('employeeName', nameRequired).notEmpty();
req.checkBody('employeeEmail', emailRequired).notEmpty();
req.checkBody('employeeEmail', emailNotValid).isEmail();
req.checkBody('employeeMobile', mobileRequired).notEmpty();
req.sanitize('employeeName').trim();
req.sanitize('employeeName').escape();
// End Validation
const errors = req.validationErrors();
console.log(errors);
if(!errors){
const employee = new Employee({
name : req.body.employeeName,
email : req.body.employeeEmail,
mobile : req.body.employeemobile,
});
employee.save(function(err){
if(err){
throw err;
}
console.log('User inserted successfully');
res.redirect('/employee-list');
});
}else{
console.log(employeeData.employeeName);
const employeeNameRequired = errors.find(el => el === nameRequired );
const employeeEmailRequired = errors.find(el => el === emailRequired);
const employeeEmailNotValid = errors.find(el => el === emailNotValid);
const employeeMobileRequired = errors.find(el => el === mobileRequired);
res.render('employee/add-employee',{
employeeData,
employeeNameRequired,
employeeEmailRequired,
employeeEmailNotValid,
employeeMobileRequired
});
}
};
And you View file will look something like this:
<div class="col-md-12">
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Add Employee Profile</h3>
<h5 class='text-aqua pull-right' style='margin-top: 0px;'>
<i class="fa fa-backward"></i> Back
</h5>
</div>
<!-- form start -->
<form method = 'post' action = '/save-employee'>
<div class="box-body">
<div class="form-group col-md-4">
<label>Name</label>
<div class='input-group'>
<span class="input-group-addon"><i class="fa fa-pencil"></i></span>
<input type='text' name='employeeName' id='employeeName' value='<%= employeeData.employeeName %>' class='form-control' placeholder='Employee Name'>
<p><%= employeeNameRequired %></p>
</div>
<div class="form-group has-error">
<span class="help-block" style="text-align:center" id="error_tagType"></span>
</div>
</div>
<div class="form-group col-md-4">
<label>Email</label>
<div class='input-group'>
<span class="input-group-addon"><i class="fa fa-pencil"></i></span>
<input type='text' name='employeeEmail' id='employeeEmail' value='<%= employeeData.employeeEmail %>' class='form-control' placeholder='Employee Email'>
<p><%= employeeEmailRequired %></p>
<p><%= employeeEmailNotValid %></p>
</div>
<div class="form-group has-error">
<span class="help-block" style="text-align:center" id="error_tagName"></span>
</div>
</div>
<div class="form-group col-md-4">
<label>Mobile</label>
<div class='input-group'>
<span class="input-group-addon"><i class="fa fa-pencil"></i></span>
<input type='text' name='employeeMobile' id='employeeMobile' value='<%= employeeData.employeeMobile %>' class='form-control' placeholder='Employee Mobile'>
<p><%= employeeMobileRequired %></p>
</div>
<div class="form-group has-error">
<span class="help-block" style="text-align:center" id="error_tagDescription"></span>
</div>
</div>
</div>
<div class="callout" id='message-container' style='display:none;'></div>
<div class="box-footer">
<button type='submit' name='saveEmployeeProfile' class='btn btn-primary'>Save</button>
</div>
</form>
</div>
</div>
Update:
For me personally, using jsonSchema validation fits best. It's very configurable and results in more readable code. For example module tv4 can be used with jsonSchema to validate req.body.

Resources