Updating text in markdown - javascript

Coding a blog website, using SimpleMDE (Markdown editor) for writing Markdown.
In app.js ,
//EDIT BLOG - FORM
app.get("/blog/:id/edit", function(req,res) {
Blog.findById(req.params.id, function(err, foundBlog) {
if(err) {
res.redirect("/blog");
} else {
res.render("editBlog", {blog : foundBlog});
}
})
})
//UPDATE BLOG
app.put("/blog/:id", function(req,res) {
req.body.blog.body = req.sanitize(req.body.blog.body);
var id = req.params.id;
Blog.findByIdAndUpdate(req.params.id, req.body.blog,{new: true}, function(err,updatedBlog) {
if(err) {
res.redirect("/blog");
} else {
res.render("showBlog", {blog : updatedBlog});
})
On using SimpleMDE, it works fine.
But on clicking the "Edit" button, the changes are saved as such:
In editBlog.ejs,
<div class="field">
<label>Text</label>
<textarea id="MyID" type="text" name="blog[body]"><%= blog.body %> </textarea>
</div>
In showBlog.ejs,
<div id="main-blog-content"><%- blog.body %></div>
Am I missing something here?

SimpleMDE is designed for writing Markdown. As such, the editor will provide Markdown when a form is submitted or when the content is accessed. If you're looking to convert it to HTML, you'll need to do so with a parsing library. SimpleMDE uses marked, if you want to maintain consistency with the preview window.
Here's how to use SimpleMDE's built-in parser to convert Markdown to HTML:
var simplemde = new SimpleMDE();
var html = simplemde.markdown("**Example** text");

Related

Add a javascript result to an image url

So what im trying to do is query a Minecraft server with javascript, and with the response i get back with the api, i want to grab the .playerlist and put the response in this url (https://cravatar.eu/avatar/ {name} /100.png) for each person connected
If someone knows a better way to achieve this, i would very much appreciate your input!
Im also pretty new to javascript, so not fully know what im doing :/
Heres the HTML that i have (i know it may be messy, its also not fully my code)
<div class="card"> <div class="icon"><img src="https://cdn.worldvectorlogo.com/logos/minecraft-1.svg"></div><div class="header">
<div class="image"> <img src="https://res.cloudinary.com/lmn/image/upload/e_sharpen:100/f_auto,fl_lossy,q_auto/v1/gameskinnyc/u/n/t/untitled-a5150.jpg" alt="" /> </div>
<h2>Server Status</h2>
</div>
<div id="rest">Loading...</div>
<img src="https://cravatar.eu/avatar/" $face "/>
</div>
And here is the javascript
//Query api at this address
var url = "https://api.minetools.eu/query/play.aydaacraft.online/25565";
$.getJSON(url, function(r) {
//data is the JSON string
if(r.error){
$('#rest').html('Server Offline.');
return false;
}
var p1 = '';
if(r.Players > 0 ){ p1 = '<br>'+r.Playerlist; }
// Text to display below
$('#rest').html('Total Online: '+r.Players+p1);
// Trying to add playerlist to html url
$('#face').html+p1;
});
Since you've pasted jQuery code, I'll submit my answer in jQuery. However, I do recommend you learn primitive JavaScript and not focus your attention just on jQuery... it's become something of a meme on StackOverflow.
Starting off, you really should be wrapping your code in $(document).ready this'll only run the code when the page has loaded.
$(document).ready(() => {
// The document is ready, let's run some code!
});
Then add your AJAX request as normal inside this bracket.
$(document).ready(() => {
let url = "https://api.minetools.eu/query/play.aydaacraft.online/25565";
$.getJSON(url, response => {
});
});
Okay, whilst writing this, I checked the URL provided by OP and saw that it was timing out so I've grabbed a sample response from the Minetools' documentation.
{
"MaxPlayers": 200,
"Motd": "A Minecraft Server",
"Playerlist": [
"Connor",
"Kamil",
"David"
],
"Players": 3,
"Plugins": [],
"Software": "CraftBukkit on Bukkit 1.8.8-R0.2-SNAPSHOT",
"Version": "1.8.8",
"status": "OK"
}
So in your JSON response, you can see that Playerlist is a array which can contain multiple things in one variable. You can also iterate through an array, which is what we'll be doing to build the image URLs.
We iterate through an array using forEach.
$(document).ready(() => {
let url = "https://api.minetools.eu/query/play.aydaacraft.online/25565";
$.getJSON(url, response => {
response.Playerlist.forEach(playerName => {
console.log(playerName);
});
});
});
//Console:
//Connor
//Kamil
//David
Now that we're iterating through the player list we can start assembling the URLs for these images and adding them to your document's body.
I've cleaned up your HTML, take note of the new div#user-images I've added. This'll be the place where jQuery will add your images from the forEach loop.
<div class="card">
<div class="icon">
<img src="https://cdn.worldvectorlogo.com/logos/minecraft-1.svg">
</div>
<div class="header">
<div class="image">
<img src="https://res.cloudinary.com/lmn/image/upload/e_sharpen:100/f_auto,fl_lossy,q_auto/v1/gameskinnyc/u/n/t/untitled-a5150.jpg" alt="" />
</div>
<h2>Server Status</h2>
</div>
<!-- This div tag will need to hide when there is no error, or say when there is. -->
<div id="rest">Loading...</div>
<!-- The user images will be added inside this div. -->
<div id="user-images"></div>
</div>
Now we have our HTML ready we can start using the jQuery function appendTo to add elements into our div#user-images.
$(document).ready(() => {
let url = "https://api.minetools.eu/query/play.aydaacraft.online/25565";
$.getJSON(url, response => {
response.Playerlist.forEach(playerName => {
$(`<img src="https://cravatar.eu/avatar/${playerName}" />`).appendTo("#user-images");
});
});
});
Your div#user-images should start filling up with the images of players from the Playerlist array.
I noticed you added a simple way of showing whether or not there's an error with the API. We can interact with div#rest to show/hide or change text depending on the success of the response.
$(document).ready(() => {
let url = "https://api.minetools.eu/query/play.aydaacraft.online/25565";
$.getJSON(url, response => {
if(response.error){
$("#rest").html("The server is offline!");
}else{
//There is no error, hide the div#rest
$("#rest").hide();
response.Playerlist.forEach(playerName => {
$(`<img src="https://cravatar.eu/avatar/${playerName}" />`).appendTo("#user-images");
});
}
});
});
And that's it really. I hope this gives you some understanding of arrays, and iterating through them, as well as some DOM functions from jQuery.

Appending fetched ejs items

Objective:
I have a button that runs a function to load more items from my Mongoose DataBase and add them to a table row. I use get to get and return data from my server side. And am following pointers from this post, but I am still unable to render what I need.
Client side code:
<main role="main">
<div class="container-fluid ">
<div class="card-columns" id="test" value="<%=deals%>">
<tbody>
<tr id="content"><% include partials/row.html %></tr>
</tbody>
</div>
</div>
<div class="container" style="max-width: 25rem; text-align: center;">
<a id="8-reload" class="btn more" onclick="loadMore(8)"></a>
</div>
<script >
const loadMore = async function(x){
const response = await fetch(`/${x}`);
if (!response.ok)
throw oops;
const data =await response.text();
console.log(data);
console.log($("#content"));
await document.getElementById('content').insertAdjacentHTML('beforeend',data);
}
</script>
Server JS request:
app.get(`/:count`, (req, res) => {
const count = parseInt(req.params.count);
database.find({}, (err, found) => {
if (!err){
res.render("more",{items:found},(err,html)=>{
if(!err){
res.send(html);
}else{
console.log(err);
}
});
} else {
console.log(err);
}
}).skip(count).limit(25);
});
when running the function nothing happens and browser console log reads the long string of html. and this for the place I want to append to:
jQuery.fn.init {}
proto: Object(0)
No errors on server console log. What am I missing?
UPDATE I tried Appending instead of to content to test and lo and behold I AM appending html, just not all of my content. int only inserts the opening and closing of the entire html template none of the content between it. Weird.
Okay looks like the big problem was two things. The first issue was I was appending to a place that the content couldn't append to. The second issue was My template started with Table rows with more content in them which would not allow other stuff to render. Once I moved my jquery to a parent id and removed the table rows everything came in fine!

How to pass variable from Jade to .JS file?

In my code below I have created an array of items in my .JS file. I was then able to pass this array to the .Jade and use each value in the array as an item in a dropdown list. I now want to pass the user input of which item they will click in the dropdown back to the server side (.js) so that I can use the user input to find more data.
My problem is that I don't know how to send the .jade variables to the server side. I want to send the "this.selectedIndex"/selected "val" so I can use it as a variable in the javascript file.
.JS
router.get('/', function(req, res) {
var projectPathArray = [];
async function main() {
var projects = await _db.listProjects();
projects.forEach(async (item) => {
var pathy = item.path;
projectPathArray.push(pathy)
})
res.render('index', { title: 'Projects', projectPathArray:projectPathArray});
}
main();
.jade
extends layout
script(src="libs/jquery-1.11.3.min.js")
link(rel='stylesheet', href='/stylesheets/style.css')
block content
h1= title
p To start, please select a project
html
body
form#test-form(action='', method='get')
select#menu1(name='menu1', size=projectPathArray.length)
each val in projectPathArray
option=val
Without understanding exactly what you want this should at least get you closer to what you are asking for.
1) Add the route to handle the post where you can retrieve the values posted back in the form using req.body.
2) In your Pug/Jade template I indented the form elements so they are under the form, added a submit button, and changed the method of the form to post.
.JS
router.post('/', function(req, res) {
console.log(req.body);
res.redirect('/');
});
router.get('/', function(req, res) {
var projectPathArray = [];
async function main() {
var projects = await _db.listProjects();
projects.forEach(async (item) => {
var pathy = item.path;
projectPathArray.push(pathy)
})
res.render('index', { title: 'Projects', projectPathArray:projectPathArray});
});
main();
.jade
extends layout
script(src="libs/jquery-1.11.3.min.js")
link(rel='stylesheet', href='/stylesheets/style.css')
block content
h1= title
p To start, please select a project
html
body
form#test-form(action='', method='post')
^
select#menu1(name='menu1', size=projectPathArray.length)
each val in projectPathArray
option=val
button(type='submit') Submit
You will need to use some mechanism for communicating from the frontend back to the server. This includes, but is not limited to, websockets and/or AJAX.

jQuery not picking up correct value from Partial View

I have a Hidden field in a Partial View
#Html.HiddenFor(model => model.Type, new { id = "Type" })
In my JS for the page in document.ready function I am trying to get the value for this Field using:
var type = $('#Type').val();
alert(type);
The value Type is set in two partial views which then Render the other Partial View as below:
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
{ Model.Type = TypeEnum.Diesel; }
<p>
#{ Html.RenderPartial("_MyOtherView"); }
</p>
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
{ Model.Type = TypeEnum.Petrol; }
<p>
#{ Html.RenderPartial("_MyOtherView"); }
</p>
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
{ Model.Type = TypeEnum.Electric; }
<p>
#{ Html.RenderPartial("_MyOtherView"); }
</p>
}
However when I naviagte between the Tabs which load the content the alert only ever fires with the 'Diesel' value - I change the HiddenFors to TextBoxFor and on screen I can see the contents of the textbox gets updated to Diesel/Petrol/Electric on moving between Tabs but I cannot figure out why the alert is not getting changed?
Unless you used "Type" as an example ID, you seem to be rendering three partial views, each containing a hidden input with ID "Type". The result is a page with three inputs with the same ID, causing a conflict if you're trying to get their value the way you did in your script.
I suggest putting classes on them, for example "hiddenInput", and then updating your script to something similar to this:
$('.hiddenInput').each(function() {
alert($(this).val();
});

Display a few lines of a text in MVC

I'm using MVC3 and wanna to display 3 lines of a Post in Blogging system and then add a link to go the rest of the post , you can see sample in most of blogs like this
this is my View :
#model IEnumerable<Blog.Web.UI.ViewModels.PostViewModel>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div>
#foreach (var item in Model)
{
<div>
<h3>
#Html.ActionLink(item.Title, "Post", "Blog", new { postId = item.Id, postSlug = item.UrlSlug }, null)
</h3>
</div>
<div>
<span>Category: </span>#item.Category
</div>
<div>
<span>Tag: </span>#item.Tag
</div>
<div>
#item.CreationDate.ToLongDateString()
</div>
<div>
#Html.DisplayTextFor(p => item.Body)
</div>
}
</div>
as it is shown
#Html.DisplayTextFor(p => item.Body)
shows whole of the post , but I wanna to do like the link I referenced , I think it is possible via javascript but I don't know How !
It looks like the example you provides trims off any extra text longer than a given length. You could do the same by modifying your ViewModel like so:
class PostViewModel
{
public string Body {get;set;}
public string ShortBody
{
get
{
return Body.Length <= 140
? Body
: Body.Substring(0, 140) + "...";
}
}
}
Then change your DisplayTextFor line to this:
#Html.DisplayTextFor(p => item.ShortBody)

Categories

Resources