is this a correct syntax for EJS technology in HTML ? The "flash object" is send from controller . Here it is my "log in" action in Controller and HTML code. I want a peace of HTML is executed base on the content of "flash object". But it doesn't work.This is controller in back end:
login: function(req, res){
var x = new LdapService();
x.login(req.body.userid, req.body.password, function(isAuth){
if(isAuth ){
res.send('successful login');
}
else{
res.view('login/index', {locals: {flash: req.flash('error', 'Wrong Credentials')}}) ;
}
});
},
=============================================
Here it is the HTML code in front end.
<% if (req.flash('error')!=''){ %>
<p>Hi</p>
<p><%- (req.flash('error')) %></p>
<div class="box-body">
<div class="alert alert-danger alert-dismissable">
<i class="fa fa-ban"></i>
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<b>Alert!</b> Wrong
</div>
</div>
<% } %>
Once you access the flash object using req.flash, its value is cleared. So the conditional test will clear the flash object.
The value is also stored in the session, so I test the session directly before displaying the flash value.
<% if(req.session.flash && req.session.flash.error){ %>
<div class="row form-row m-l-20 m-r-20 xs-m-l-10 xs-m-r-10">
<div class="alert alert-error">
<button class="close" data-dismiss="alert"></button>
<%- req.flash('error') %>
</div>
</div>
<% }%>
It's not entirely clear why you need to use flash messages in this case, since you're setting the message and displaying it in the same request. Flash messages are more appropriate when you're setting a message and then redirecting, because the code before the redirect doesn't have the opportunity to set the view locals directly. You could just do:
res.view('login/index', {locals: {flash: {'error':'Wrong Credentials'}}});
and in your template:
<% if((flash = {} || flash) && flash.error){ %>
<div class="row form-row m-l-20 m-r-20 xs-m-l-10 xs-m-r-10">
<div class="alert alert-error">
<button class="close" data-dismiss="alert"></button>
<%- flash.error %>
</div>
</div>
<% }%>
If you were redirecting from another view, then you could use flash messages and keep the same template. In the action you're redirecting from, you'd set a flash message:
req.flash('error', 'my error message');
res.redirect('/someOtherLoginRoute');
and in the action you redirected TO, do:
res.view("login/index", {locals: {flash: req.flash()}});
It's kind of a contrived example, but there you have it.
Related
Guys I need to send request to servlet named sendOTP when click the change password button I also want to send the parameter named email along with it.How to do that? Please help!
<html>
<body>
<h1>ADMIN</h1>
<div class="btn-group" >
<button>VIEW ORDERS</button>
<button>VIEW PRODUCTS</button>
<button>VIEW SELLER</button>
<button>SEND REQUEST</button>
<a href="http://localhost:8090/Bootathon2_war_exploded/SendOTP?email="+<%=email%>><button>CHANGE PASSWORD</button></a>
<button>LOGOUT</button>
</div>
</body>
<%!
String email;
%>
<%
email=request.getSession().getAttribute("email").toString();
%>
</html>
I want to add a delete functionality to a button that's part of a card which is encapsulated in a form this is as far I got:
<form class="form-events" action="/delete" method="post">
<% events.forEach( function (event) { %>
<div class="card col-lg-3" style="width: 18rem;">
<img class="card-img-top">
<div class="card-body">
<h5 class="card-title"><%= event.title %></h5>
<p class="card-text"><%= event.description %></p>
<p class="card-text"><%= event.date %> </p>
<p class="card-text"><%= event.capacity %></p>
Update
<button onclick="this.form.submit()" value="<%= event._id %> " name="deletebtn" class="btn btn-danger">Delete</button>
</div>
</div>
<% }); %>
</form>
And this is the route for it:
// Delete an event
app.post("/delete", function (req, res) {
const deletedItemId = req.body.deletebtn;
Event.findByIdAndRemove(deletedItemId, function (err) {
if (!err) {
console.log("Successfully deleted");
res.redirect("/admin");
} else {
console.log(err);
}
});
});
I get this error when I press the delete button:
reason: Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex
characters
Okay, this is how I solved I am not sure if it's the correct way, but it works.
Form admin.ejs
<% events.forEach( function (event) { %>
<form class="form-events" action="/delete" method="post">
<div class="card col-lg-3" style="width: 18rem;">
<img class="card-img-top">
<div class="card-body">
<h5 class="card-title"><%= event.title %></h5>
<p class="card-text"><%= event.description %></p>
<p class="card-text"><%= event.date %> </p>
<p class="card-text"><%= event.capacity %></p>
Update
<button name="deleteBtn" value="<%=event._id%>" type="submit" class="btn btn-danger">Delete</button>
</div>
</div>
<% }); %>
</form>
The app.js for the route
app.post("/delete", function (req, res) {
const deletedItemId = req.body.deleteBtn;
Event.findByIdAndDelete(deletedItemId, function (err) {
if (!err) {
console.log("Successfully deleted");
res.redirect("/admin");
} else {
console.log(err);
}
});
});
Now it works perfectly and for the database, but most stuff I googled where showing to use
/*for the route */
app.delete(“delete/:id”), function()
/*for the form */
<form method="POST" action="/delete/<%= event._id%>?_method=DELETE">
<button type="submit">Delete</button>
</form>
which I tried but got ran into some errors again and return to the original one which works, I don't really understand the whole app.post, app.delete because you also use the action /delete and then you can just remove it using mongoose, also I am not sure but for the form method in HTML it's said you only can use post and put, which confused me even more....
some friends and I have started a team project but we are stuck at this point. We made a function of the site to add comments under every post. The problem is that when submit is clicked it adds the comment but doesn't refresh the page which causes some problems. The author stays "anonymous" and when refresh button is clicked it shows an alert:
The page that you're looking for used information that you entered. Returning to that page might cause any action you took to be repeated. Do you wish to continue?
However, if we just type the URL again and click ENTER everything is good: the author shows up and the comment appears only once. So the only solution for us is to redirect to the same page. Here is the form:
<div style="text-align: left">
<div><i>Leave your comment</i>
</div>
<form method="post">
<fieldset>
<p>
<textarea rows="10" class="form-control" type="text" id="1" name="commentText" style="height: 100px"></textarea>
</p>
<p>
<input type="submit" name="buttonSubmit" onclick="redirect" value="Add comment" class="btn btn-default" style="" />
</p>
</fieldset>
</form>
</div>
This is how the comments are printed on the page:
<h3>Comments</h3>
<br>
<div>
#foreach (var comment in ViewBag.Comments) {
<section class="row">
<article class="post col-md-12">
<div class="about">
Posted on <i>#comment.Date</i>
#if (comment.AuthorId != null) { #: by <i>#comment.Author.FullName</i>
}else { #: by <i>anonymous</i>
}
</div>
<div class="body">#comment.Text</div>
</article>
</section>
}
</div>
Thanks in advance!
Use the #Ajax.BeginForm() helper.
In the AjaxOptions(), you'll want to set the Httpmethod to "Post", InsertionMode.InsertBefore (or After depending on where you want new comments), and UpdateTargetId = "your-comment-div".
You'll need to include jquery.unobtrusive-ajax.js so the Ajax helper works correctly. You can use the nuget package manager to pull it in. Be sure to add it to your jquery bundle.
Then, you need to create the post action in your controller to accept the comment params and return a partial view.
Doing thIs keeps the Ajax confined to a razor helper and controller method.
View:
#using (Ajax.BeginForm("AjaxAddComment",
"MyController",
/* route params */,
new AjaxOptions()
{
InsertionMode = InsertionMode.InsertBefore,
UpdateTargetId = "commentsDiv",
HttpMethod = "Post"
}, htmlAttributes: new { /* ... */ }))
{
<div class="form-horizontal">
#* comment form... *#
</div>
}
...
<div id="commentsDiv">
<div class="comment">...</div>
<div class="comment">...</div>
</div>
Controller:
[HttpPost]
//[ValidateAntiForgeryToken]
public async Task<PartialView> AjaxAddComment(string comment, /*...other params*/)
{
var newComment = ... // comment viewModel
// add comment to db
await db.SaveChangesAsync();
return PartialView("_CommentPartial", newComment);
}
_CommentPartial:
<div class="comment">
...
</div>
Hi I am learning backbone.js and as a part of a project I want to send a variable from my view.js file in Backbone to the associated template(.html). How should i do it?
Currently I try to do the following but fail:
In View.js:
$( ".result" ).html( displayChoice );
In html template:
<% if(!displayChoice.localeCompare("true")) { %>
<div class="name" id="choices"><%- choices[i].choice %></div>
<% } %>
Please tell me what is wrong in this approach.
I'm new to this and have no idea how it must work.
I have a partial view in a foreach in my view that lists all news comments for that news article.
I have a textarea with a post button where the user can submit further comments on this news article.
The new news article must be appended to the list, without doing a location.reload. I was told do use AJAX, not JSON.
Here's my controller:
[HttpGet]
[NoCache]
public ActionResult SetCommentOnNews(int newsId, string newsComment) ??
{
var currentUser = ZincService.GetUserForId(CurrentUser.UserId);
ZincService.NewsService.SetCommentOnNews(newsId, newsComment, currentUser.UserId);
return Json(new { success = true }, JsonRequestBehavior.AllowGet); ??
}
<div class="news-comment-content" id="news-comment-content">
<% if (Model.Results != null) {
foreach (var newsItem in Model.Results.NewsComments) %>
<% { %>
<% Html.RenderPartial("~/Views/Home/SetCommentOnNews.ascx", newsItem); %>
<% } %>
</div>
my partial:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Zinc.Web.Areas.News.ViewModels.Home.NewsCommentsViewModel>" %> //this also not right
<div class="news-post-list-item">
<div class="news-post-user-info-wrapper">
<div class="avatar">
<img width="52" height="52" alt="Avatar" src="/ThemeFiles/Base/images/User/user-avatar.png"/>
</div>
<div class="who-and-when-box">
<%: newsItem.CommentDate %>
<br />
<br />
<%: ViewBag.UserName %>
</div>
<div class="news-comment"><%: newsItem.NewsComment %></div>
<div class="clear"></div>
</div>
<div class="clear"></div>
</div>
<div class="header">
<h3>
Leave a comment
</h3>
</div>
<div>
<textarea id="textareaforreply" rows="3" cols="160"></textarea>
</div>
<div>
Post
</div>
<script type="text/javascript">
function PostNewsComment(newsId) {
$("post-button").click(function () {
var jqxhr = $.getJSON("<%= //Url.Action("SetCommentOnNews", "Home", new { area = "News" }) %>?newsId=" + newsId + "&newsComment=" + $("#textareaforreply").text(), function (data) {
if (data.success) {
alert($("#textareaforreply").text());
$('#news-comment').append($("#textareaforreply").text());
}
});
}
</script>
The above JS is what I have and must inject HTML in to the list using AJAX?
I have NO idea how to do this. Can some one help please?
Thanks
To inject HTML into a list using AJAX I would use Knockoutjs with templates instead of partial views. Knockout can be used to render the information in the browser. Views are for rendering server side, which does not jibe well with AJAX.
What do you mean when you say, "I was told do use AJAX, not JSON". AJAX uses JSON as a method for serializing the data that is sent over the network. Are you referring to the JQuery methods ajax versus getJSON? getJSON is just a wrapper around the ajax method that configures it specifically to retrieve JSON using the HTTP GET verb. Either will work fine, but ajax does give you more control in configuring the request.