Adding comment features to blog using express and handlebars - node.js

I'm trying to create a blog site that has the ability to comment on a blog/article. I have the end point
app.get('/post/:slug', function(req, res) {
var _slug = req.params.slug;
var blog_post = _.findWhere(_DATA, { slug: _slug });
if (!blog_post) return res.render('404');
res.render('post', blog_post);
});
that handles the display of a blog/article using HandleBars. It retrieves a post from database _DATA and simply display it using the template post.handlebars. It right now does nothing else.
I would like to add the ability to comment on this article. I'm very new to web programming and don't know how to handle requests like that. Right now, my idea is to add
<article>
<form method="POST" action="/comment">
<div class="input-field">
<label>Comment:</label>
<textarea type="text" name="comment" rows="20" placeholder="What's on your mind?"></textarea>
</div>
<button type="submit">Add Comment</button>
</form>
</article>
to the bottom of my post.handlebars and add the end point app.post('/comment', function(req, res) {});
But this presents multiple problems, namely, how would I know which article I'm commenting on? In this new end-point, my req.body would contain nothing except the contents of the comment.
What is the proper way to handle this?

Put the ID of your article in the comment form as an hidden input. When you'll submit the form you'll get the article-id value.
I've used handlebar to place the article id in the form change the value of article.id according to your data.
<article>
<form method="POST" action="/comment">
<div class="input-field">
<label>Comment:</label>
<textarea type="text" name="comment" rows="20" placeholder="What's on your mind?"></textarea>
</div>
<input type="hidden" name="article-id" value="{{article.id}}">
<button type="submit">Add Comment</button>
</form>
</article>

Related

why summernote not retrieving data into textarea for editing the text or for changes

I am using summernote rich text editor, and I want to edit my posted data(stored in DB). I am sending the value to the text area and inputs but not showing into the text area and showing into the input. kindly share some solutions and suggestions with me. any jquery and js function like this...
here is rendered data to web page
route.get('/edit/:id', async (req, res) =>{
const id = req.params.id
const article = await Article.findById(id)
res.render('editarticle',{article:article})
})
and here is ejs or HTML
<%- include('header'); -%>
<div class="container-9">
<h2>Create Article Here</h2>
<hr>
<form action="/create/blog" method='post'>
<input type="text" name="title" id="" placeholder="Enter Title" value='<%=article.title%>'/>
<input type="text" name="description" id="dics" placeholder="Enter Description" value='<%=article.discription%>'/>
<hr>
<button id='btn-post' type="submit">Post</button>
<textarea name='content' id="body" rows="10" value="<%=article.content%>" ></textarea>
</form>
</div>
<%- include('footer'); -%>
I have solved this problem with help of one line of code. I have got the solution after 2 month
var value = $('#value').val()
console.log(value);
$('textarea#body').summernote('pasteHTML', value);
if want to render the HTML for edit this will work, var value = $('#value').val() it just receiving the value (HTML) from the backend and $('textarea#body').summernote('pasteHTML', value); this line of code pesting the HTML into summernote editor.
#tushar Very useful !!
I use it on summer note as like
Put Content in a div, and set it display none
<div id="contentDumpDiv" style="display:none;">
<?php echo $post['content'] ?>
</div>
then use this javascript code
var value = $('#contentDumpDiv').html();
$('textarea#saContent').summernote('pasteHTML', value);

How to get data from a form dropdown select element?

I'm using Express.js and trying to get form data of a dropdown select element,
I tried with body-parser but what I get with eq.body.method_select is undefined.
I didn't find much info about how to do this on the web.
Here is my code html code:
<form action="url_analyse">
<div class="col-lg-6">
<div class="input-group">
<select class="custom-select mb-2 mr-sm-2 mb-sm-0" name="method_select" id="inlineFormCustomSelect">
<option value="5">Regular Search (Short)</option>
<option value="10">Intense Search (Long)</option>
<option value="20">Deep Search (Very Long)</option>
</select>
<input type="text" name="url_input" class="form-control" placeholder="Enter URL">
<span class="input-group-btn">
<button class="btn btn-secondary">Go!</button>
</span>
</div>
</div>
Here is my js code:
app.get('/url_analyse', function(req, res) {
console.log(req.body.method_select);
})
Hope you can help me with that.
Thank you.
There are two issues here:
You might want to explicitly add the leading forward slash: action="/url_analyse"
The default form submission HTTP method is GET, which means that form fields will be passed in the query string portion of the URL. This means you will instead need to access req.query to get at the form fields. You only need body-parser and req.body when you use POST and other methods (with the appropriate enctype) to submit your form.

Getting a classname or attribute of a DOM element using post in Node and Express

I have a form that I am submitting using post. I can retrieve input values, however I also want to retrieve the class name or attribute of a div within a form.
html:
<form method='post' action='/formResult'>
<input type='text' name='someInput' />
<div class="stateAlpha" customAttr="alpha"></div> <!-- want 'alpha' -->
<button type="submit" class="btn btn-default">Submit</button>
</form>
node/express:
router.post('/formResult', function(req, res, next){
res.render('formResult', { someInput: req.body.someInput, someState: req.body.??? });
});
You'll need to intercept the submit event of the form, and put the class info into a hidden field. In pure JavaScript:
<form method='post' class='myForm' action='/formResult'>
<input type='text' name='someInput'>
<input type='hidden' name='state'>
<div class="stateAlpha" customAttr="alpha"></div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<script>
document.querySelector('.myForm').addEventListener('submit', function(evt) {
var alpha = evt.target.querySelector('[customAttr="alpha"]');
var hiddenState = evt.target.querySelector('[name="state"]');
hiddenState.value = alpha.classList.join(' ');
});
</script>
Note that I added a class to the form, and used that to select the form; that's because you may have more than one form on the page, and you want to select the right one. Also note that inside the submit listener, I don't use document as the base of my selection, but evt.target; that's because you might have elements with customAttr='alpha' elsewhere in your document.
Once I have the div with the class you want to identify, I get the hidden input element, and set it's value property to the div's class list (remember any element can have more than one class, so classList is an array, which I just join using spaces).
If you're using jQuery, it gets a little shorter:
<form method='post' class='myForm' action='/formResult'>
<input type='text' name='someInput'>
<input type='hidden' name='state'>
<div class="stateAlpha" customAttr="alpha"></div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<script>
$(document).ready(function() {
$('.myForm').on('submit', function() {
var $alpha = $(this).find('[customAttr="alpha"]');
$(this).find('[name="state"]')
.val($alpha.get(0).classList.join(' '));
});
});
</script>
The DOM is client-side and when you post the form only the values of the fields are posted, nothing else. To achieve what you are trying to do you can create a hidden field that stores the value of your class like this.
<input type="hidden" value="stateAlpha" name="myFieldName" />
This will then get sent in the form post.

cant make the gmaps.js search functions

i have made this simple app with gmaps.js but i need the search functions like they show it here:
http://hpneo.github.io/gmaps/examples/geocoding.html
i looked at the source code and all but it aint working.. The search button reloads the page...
my code is a follows:
<script>
$('#geocoding_form').submit(function(e){
e.preventDefault();
GMaps.geocode({
address: $('#address').val().trim(),
callback: function(results, status){
if(status=='OK'){
var latlng = results[0].geometry.location;
map.setCenter(latlng.lat(), latlng.lng());
}
}
});
});
</script>
<form method="post" id="geocoding_form">
<label for="address">Address:</label>
<div class="input">
<input type="text" id="address" name="address" />
<input type="submit" class="btn" value="Search" />
</div>
</form>
<div id="map"></div>
the rest is loaded in from scripts.js you can see it in sourcecode. Why is this happening and how can i fix this?
The web app is located here, http://travelers.work/trein/
You need to change
map.setCenter(latlng.lat(), latlng.lng());
to
map.setCenter(latlng);
because the search returns a LatLng object as a result, and that's what is needed as an input for setCenter.
Here's a JS demo with your code: http://jsfiddle.net/DuRhR/3/
EDIT after comments:
Alternatively, you can pass to setCenter a LatLngLiteral
map.setCenter({lat: latlng.lat(), lng: latlng.lng()});

Shortcut to adding req values to a response for rendering in Express View

I'm using Node/Express (most recent production versions)
I have a form where I collect new account info. The user can add a username, etc.
In the view handler, I check a mongodb database to see if the username is unique. If it is not, I generate a message and reload the original view. Since the original request was a post, all of the data the user posted is in req.body. I would like to add the data the user submitted on the response. I could do it by specifically adding each value to the response. But isn't there an easier way to add all the request data back to the response? And is there a way to render that in the view (i'm using ejs) I tried res.send(JSON) coupled with ejs variables. Doing so generates errors saying the variables aren't available.
Here's my function (ignore the users.createUser(req) - it's not finished yet):
createAccount: function(req, res, next){
users.createUser(req);
res.render('create_account', {
layout: 'secure_layout',
title: 'Create Account',
givenName: req.body.givenName,
username: req.body.username,
familyName: req.body.familyName
});
},
And here's my view:
<form action="/createAccount" method="post">
<div>
<label>First Name:</label>
<input type="text" name="givenName" value="<%= givenName %>"/><br/>
</div>
<div>
<label>Last Name:</label>
<input type="text" name="familyName" value="<%= familyName %>"/><br/>
</div>
<div>
<label>Username:</label>
<input type="text" name="username" value="<%= username %>"/><br/>
</div>
<div>
<label>Password:</label>
<input type="password" name="password"/>
</div>
<div>
<input type="submit" value="Submit"/>
</div>
</form>
It seems overly complex to have to add each of the values. I tried {body: req.body} but values were never added to the view.
I'm not quite sure what you're after, but if you want to render an ejs view with data that was on the request body, you would do something along these lines:
app.post('/foo', function(req, res, next) {
res.render('view', {body: req.body});
});
view.ejs:
<ul>
<% for(var key in body) { %>
<li><%= key %>: <%= body[key] %></li>
<% } %>
</ul>

Resources