ExpressJS Comma Separating Values - javascript

I am trying to create a tagging system for my records, and assumed that I would be able to create separate tags by using req.body.tags.trim().split(","); on my post method, but all of the comma separated values I provide are displated as one URL.
Values being written:
Values displayed and hovered over:
POST method:
router.route('/admin/posts/create')
// START POST method
.post(function(req, res) {
console.log("New instance");
var blogpost = new Blogpost(); // create a new instance of a Blogpost model
blogpost.title = req.body.title; // set the blog title
blogpost.featureImage = req.body.featureImage; // set the blog image
blogpost.blogUrl = blogpost.title.toLowerCase().replace(/\s+/g,"-");
blogpost.author = req.body.author; // set the author name
blogpost.tagline = req.body.tagline; // set the tagline
blogpost.content = req.body.content; // set the blog content
blogpost.category = req.body.category; // set the category
blogpost.tags = req.body.tags.trim().split(","); // set the tags
//Save Blog Post
blogpost.save(function(err) {
if (err)
res.send(err);
res.redirect(303, '/'); //NEEDS TO BE CHANGED
});
}) // END POST method
.get(isLoggedIn, function(req, res, blogpost) {
res.render('pages/blogpost-create', {
blogpost : blogpost
});
});
Blogpost-create.ejs:
<form action="/admin/posts/create" method="POST">
Header Image: <input type="file" id="files"/>
<p id="status">Please select a file</p>
<div id="preview"><img src="/images/event-placeholder.png"></div>
<input type="hidden" id="feature-image" name="featureImage" value="/images/event-placeholder.png" />
Title: <input type="text" name="title" required></input><br>
Author:
<select name="author">
<option value="Author">Blog Author</option>
</select><br>
Category:
<select name="category">
<option value="Test 1">Test 1</option>
<option value="Test 2">Test 2</option>
<option value="Test 3">Test 3</option>
<option value="Test 4">Test 4</option>
</select><br>
Tagline: <input type="text" maxlength="155" name="tagline" required><br>
Content:<br>
<textarea name="content" id="blog-editor" rows="10" cols="80">
</textarea>
<br>
Tags: <input type="text" name="tags" required>
<br>
<input type="submit" value="Submit">
Blogpost.ejs (Where values are displayed):
<header>
<% include ../partials/header %>
</header>
<div class="container">
<div class="col-md-12">
<div id="blog-content">
<h1><%= blogpost.title %></h1>
<img src="<%= blogpost.featureImage %>" class="img-responsive" id="blogpost-feature-image">
<h3 class="blog-date"><%= blogpost.dateString %></h3>
<h3 class="blog-category"><%= blogpost.category %></h3>
<h3 class="blog-tagline"><i><%= blogpost.tagline %></i></h3>
<p><%- blogpost.content %></p>
<%= blogpost.tags %>
</div>
</div>
</div>

Yeah, you're writing them all into one anchor in your ejs template.
Something like this:
<ul>
<% for(var i=0; i<blog.tags.length; i++) { %>
<li>
<a href='/tags/<%= blog.tags[i] %>'>
<%= blog.tags[i] %>
</a>
</li>
<% } %>
</ul>
I'm assuming that your save logic successfully saves the array as you think, but that's worth checking as well

Related

Fetch API post data is not transferring data to views.py in Django

I am creating a Django app and for that I am trying to access data received from a POST request, using JavaScript fetch API but it is not working. I can see that the page is not refreshing after hitting the submit button because of the e.preventDefault(); but the values are not getting fetched at all. I can't get what my mistake is. I have tried to remove all unnecessary parts to debug. Please let me know where am I going wrong.
views.py
def home(request):
if request.method=="POST":
options_value=request.POST['dropdown_val']
value=request.POST['val']
print(options_value,value)
index.html
<form method="POST" action="" id="form">
{% csrf_token %}
<div class="d-flex justify-content-center" style="margin-top: 6rem">
<div class="dropdown" style="display: flex" id="dropdown">
<select
class="form-select"
aria-label="Default select example"
name="options_value"
id="dropdown_val"
>
<option disabled hidden selected>---Select---</option>
<option value="1">Profile UID</option>
<option value="2">Employee ID</option>
<option value="3">Email ID</option>
<option value="4">LAN ID</option>
</select>
</div>
<div class="col-3 bg-light" style="margin-left: 2rem">
<input
type="text"
class="form-control"
id="in3"
type="text"
placeholder="Enter Value"
name="value"
id="value"
/>
</div>
<div style="margin-left: 2rem">
<input
class="btn btn-primary"
type="submit"
value="Submit"
style="background-color: #3a0ca3"
/>
</div>
</div>
</form>
<script>
let form = document.getElementById("form");
let dropdown_val = document.getElementById("dropdown_val");
let val = document.getElementById("value");
const csrf = document.getElementsByName("csrfmiddlewaretoken")[0].value;
form.addEventListener("submit", (e) => {
e.preventDefault();
const newform = new FormData();
newform.append("dropdown_val", dropdown_val.value);
newform.append("val", val.value);
newform.append("csrfmiddlewaretoken", csrf);
fetch("", {
method: "POST",
body: newform,
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch(error => {
console.error('Error:', error);
});
});
</script>
The problem is that you have 2 id tags in the input field:
<input
type="text"
class="form-control"
id="in3" <--- problem is here
type="text"
placeholder="Enter Value"
name="value"
id="value"
/>
remove the id='in3' and it should work. You can check that error in the Console of the browser when you submit the form.

Can't read the form elements

I can't get the values of these three fields; it only returns an empty value (a space).
The ids are correctly set in the form.
<script>
const data = {
id: document.getElementById('idbook').value,
name: document.getElementById('namebook').value,
price: document.getElementById('pricebook').value
};
function myFunction(){
const http = new easyHTTP;
http.put('https://otg0gf6qw5.execute-api.us-east-2.amazonaws.com/books',
data, function(err, post){
if(err) {
console.log(err);
} else {
console.log(post);
}
});
</script>
<!DOCTYPE html>
<html>
<body>
<div class="container">
<form method="post" id="save" action="javascript:myFunction()">
<h1>Insert Book</h1>
<div class="field">
<label for="id">ID Book:</label>
<input type="text" id="idbook" name="id"/>
<small></small>
</div>
<div class="field">
<label for="id">Name Book:</label>
<input type="text" id="namebook" name="nameBook"/>
<small></small>
</div>
<div class="field">
<label for="id">Price Book:</label>
<input type="text" id="pricebook" name="priceBook"/>
<small></small>
</div>
<div class="field">
<button type="submit" class="full">SAVE BOOK</button>
</div>
</form>
</div>
When I enter the values, and click on SAVE I get an empty json, i.e .:
{"id":"","name":"","price":""}
with error:
"One or more parameter values are not valid. The AttributeValue for a key attribute cannot contain an empty string value. Key: id"
The problem is that you are getting the values from the input fields as soon as the script runs, so you will get empty strings because the inputs at that point are empty.
To get the input values after the form is submitted, put the data variable inside the myFunction() method, it's important to read the values right before sending the data.
Example
<script>
function myFunction() {
const data = {
id: document.getElementById('idbook').value,
name: document.getElementById('namebook').value,
price: document.getElementById('pricebook').value
};
const http = new easyHTTP;
http.put('https://otg0gf6qw5.execute-api.us-east-2.amazonaws.com/books', data, function(err, post) {
if(err) {
console.log(err);
} else {
console.log(post);
}
});
};
</script>
I don't know if this is what you mean, but I did let the data save in the console log when you press submit
<div class="container">
<form method="post" id="save" action="javascript:myFunction()">
<h1>Insert Book</h1>
<div class="field">
<label for="id">ID Book:</label>
<input type="text" id="idbook" name="id"/>
<small></small>
</div>
<div class="field">
<label for="id">Name Book:</label>
<input type="text" id="namebook" name="nameBook"/>
<small></small>
</div>
<div class="field">
<label for="id">Price Book:</label>
<input type="text" id="pricebook" name="priceBook"/>
<small></small>
</div>
<div class="field">
<button type="submit" class="full">SAVE BOOK</button>
</div>
</form>
<script>
function myFunction(){
const data = {
id: document.getElementById('idbook').value,
name: document.getElementById('namebook').value,
price: document.getElementById('pricebook').value
};
console.log(data);
}
</script>
</div></body></html>

Search by Name Category/SubCategory using Javascript on laravel view

I had some problems with the task. I'm not very good with javascript. Please help.
I display categories as form and I want to when the form to be typed to display products that are set for each category and sub-category. In the next task I have to make sure that when the form is typed, the categories show up and, also without refreshing the page.
code on product_upload.blade.view
<div class="form-group row" id="category">
<label class="col-md-3 col-from-label">{{translate('Category')}}</label>
<div class="col-md-8">
<select class="form-control aiz-selectpicker" name="category_id" id="category_id" data-live-search="true" required>
#foreach($categories as $category)
<option value="{{$category->id}}">{{ $category->getTranslation('name') }}</option>
#endforeach
</select>
</div>
</div>
<div class="form-group row" id="subcategory">
<label class="col-md-3 col-from-label">{{translate('Subcategory')}}</label>
<div class="col-md-8">
<select class="form-control aiz-selectpicker" name="subcategory_id" id="subcategory_id" data-live-search="true" required>
</select>
</div>
</div>
My script :
function get_subcategories_by_category(){
var category_id = $('#category_id').val();
$.post('{{ route('subcategories.get_subcategories_by_category') }}',{_token:'{{ csrf_token() }}', category_id:category_id}, function(data){
$('#subcategory_id').html(null);
for (var i = 0; i < data.length; i++) {
$('#subcategory_id').append($('<option>', {
value: data[i].id,
text: data[i].name
}));
$(".aiz-selectpicker").selectpicker();
}
get_subsubcategories_by_subcategory();
});
}
$('#category_id').on('change', function() {
get_subcategories_by_category();
});
$('#subcategory_id').on('change', function() {
get_subsubcategories_by_subcategory();
});
and my controller :
public function get_subcategories_by_category(Request $request)
{
$subcategories = SubCategory::where('category_id', $request->category_id)->get();
return $subcategories;
}
But that wont work.

Select option dropdown with Node.js, MySQL and EJS

I would like to make a drop-down list with the data from my MySQL database, in this case I am trying to make when filling out my "create budgets" form to extract the names from the "customer" table and place them in a select option, I'm using EJS. However, I also have problems when passing EJS data since it gives me an error in the browser (Data not defined)
This is my controller to save data:
controller.save = function(req, res, next) {
const data = req.body;
req.getConnection((err, conn) => {
conn.query('SELECT nombre FROM clientes', (err, row) =>{
res.render('presupuestos_create', {
datos: row
})
});
conn.query('INSERT INTO presupuestos set ?', [data], (err, row) => {
res.redirect('/presupuestos');
});
});
};
And this is mi EJS:
<form action="/presupuestos/add" method="POST">
<div class="mb-3">
<label for="cliente" class="form-label">Cliente</label>
<select class="form-select" id="cliente" name="cliente" tabindex="1" required>
<option>----</option>
<%for(var i=0; i < datos.length; i++){%>
<option value="<%= datos[i] %>"><%= datos[i] %></option>
<%}%>
</select>
</div>
to populate from db > ejs
<select class="form-select" id="cliente" name="cliente" value="<%= datos%>" tabindex="1" required>
<% for(var i=0; i < datos.length; i++) { %>
<option
<%= datos[i].datos %>
</option>
<%}%>

How to create self referencing MongoDB schema and post routes using nodejs?

I am trying to create parent-child like nested system where child has same schema as of parent.Below is my parent schema, here children refers to the parentSchema again,
var mongoose = require("mongoose");
var parentSchema = new mongoose.Schema({
name: String,
children:[
{
ref: this
}
],
});
module.exports = mongoose.model("Parent", parentSchema);
Routes looks like this
app.get("/", function(req, res){
Parent.find({}).populate("children").exec(function(err, allParents){
if(err){
console.log(err);
}else{
res.render("index",{parents: allParents});
}
});
});
app.post("/", function(req,res){
var name = req.body.name;
var desc = req.body.desc;
var newParent = {name: name, description: desc}
Parent.create(newParent, function(err, newlyCreate){
if(err){
console.log(err);
}else{
res.redirect("/");
}
});
});
app.post("/:id", function(req, res){
Parent.findById(req.params.id, function(err, parent){
if(err){
console.log(err);
res.redirect("/");
}else{
parent.children.push(req.body.child);
parent.save();
console.log(parent.children);
res.redirect("/");
}
});
});
The problem is when I send data from form to post route it prints it but after pushing it into parent.children and then printing parent.children is shows null. Where is the problem???
EJS page looks like below:-
<form action="/" method="POST">
<div class="form-group">
<input type="text" name="name" placeholder="Name">
</div>
<div class="form-group">
<input type="text" name="desc" placeholder="Description">
</div>
<div class="form-group">
<button class=btn-primary btn-block">Submit</button>
Go Back
</div>
</form>
<div class="row">
<% parents.forEach(function(module){%>
<ul class="list-group">
<li class="list-group-item" style="margin-bottom: 5%;">
<h2><%= module.name%></h2>
<%= module.description %>
<% console.log(module.children) %>
<%module.children.forEach(function(node){%>
<% console.log(node) %>
<%});%>
<div class="container">
<div class="row">
<div>
<form action="/<%= module._id %>" method="POST">
<div class="form-group">
<input type="text" name="name" placeholder="Name">
</div>
<div class="form-group">
<input type="text" name="desc" placeholder="Description">
</div>
<button>Submit</button>
</form>
</div>
</div>
</div>
</li>
</ul>
</div>
<% }); %>
</div>
Can anyone tell where is the problem in above code or can anyone suggest any other way to make this type of parent-child structure????
It seems that parent.save() is asynchronus. Maybe you can try this instead.
parent.save().then(()=>{
console.log(parent.children);
res.redirect("/");
});
or you can use async-await after putting async before function definition,
await parent.save();
console.log(parent.children);
res.redirect("/");
Please do write in comment if problem still persists.

Categories