pass pug input element content to javascript function? - javascript

I am trying to insert, delete, and update data on a data base with html buttons. To do this i am using a pug page that is called by node express, and it all works fine. Until i try to insert data into my database. so i have this in my pug file
script(src='editor.js')
...
p Item Type *required*<br/>
input(type="text", id="iType", name="iType")
p Item name *required*<br/>
input(type="text", id="name", name="Name")
p Item price *optional*<br/>
input(type="text", id="price", name="Price")
p Item ABV *optional*<br/>
input(type="text", id="desc", name="ABV")
p Item description *optional*<br/>
input(type="text", id="desc", name="Desc")
button(id="addItemBtn" onclick="updateMenuItem("+document.getElementById('iType').value+","+document.getElementById('name').value+","+document.getElementById('Price').value+","+document.getElementById('ABV').value+","+document.getElementById('Desc').value+")") add
and with it i am trying to pass the contents of the input element to my javaScript function in editor.js
function updateMenuItem (itype,name,price,abv,desc) {
//set up connection variables for the sql query
var conn = new sql.ConnectionPool(sqlconfig);
var sqlreq = new sql.Request(conn);
//initiate the connection
conn.connect(function (err) {
//throw an error if the page cannot connect to the server
if (err) {
console.log(err);
return;
}
//
sqlreq.query("insert into food '"+itype+"','"+name+"','"+price+"','"+abv+"','"+desc+"'"), function () {
console.log('OK')
};
})
};
what am i doing wrong here?

The syntax should be:
button(id="addItemBtn" onclick="updateMenuItem(document.getElementById('iType').value, document.getElementById('name').value, document.getElementById('Price').value, document.getElementById('ABV').value, document.getElementById('Desc').value)") add

Related

How to do update in listing for web by using firebase

I am creating admin panel in website and I am using firebase as a database in backend.I am able to display listing but when I click on the particular listing there status should change from 'pending' to 'accept' but it doesnt.I dont know where I did mistake.Please give suggestion and I attach js file and database screenshot
pl.js
var firebaseheadingRef = firebase.database().ref().child("user");
firebaseheadingRef.on('child_added',datasnapshot=>{
var title= datasnapshot.child("listing").child("title").val();
var userid= datasnapshot.child("username").val();
var type= datasnapshot.child("listing").child("title").val();
var publisheddate= datasnapshot.child("listing").child("publish").val();
var expirydate= datasnapshot.child("listing").child("expire").val();
$("#tablebody").append("<tr><td>"+title+"</td><td>"+userid+"</td><td>"+type+"</td><td>"+publisheddate+"</td><td><button type=button id=accept onclick=accept()>Accept</button><button type=button>Reject</button></td></tr>");
});
function accept()
{
firebaseheadingRef.on('child_changed',datasnapshot=>{
datasnapshot.child("listing").child("status").update({"status":"accept"});
setCommentValues(postElement, data.key, data.val().text, data.val().author);
});
}
database
listing display picture where I click on accept button then update of status should done
There are two places where you need to change your code:
First, in the code that generates the table, you have to pass the id of the node to the function call, as follows. You get the node id with the key property of the DataSnapshot.
.....
$("#tablebody").append("<tr><td>"+title+"</td><td>"+userid+"</td><td>"+type+"</td><td>"+publisheddate+"</td><td><button type=button id=accept onclick=accept('" + datasnapshot.key + "')>Accept</button><button type=button>Reject</button></td></tr>");
...
And secondly you have to write your accept() function in such a way it updates the database value, with the set() method. Like the following
function accept(userId) {
var nodeRef = firebase.database().ref("/user/" + userId + "/listing/status");
return nodeRef.set('accept');
}

Split string when comma is inserted and add it to a string array

I have an input that converts strings into 'styled tags' when the user types a comma, then, when the form is submitted, the strings are pushed into an array called 'content'.
On the EJS views, I am printing the result like <%= course.content %> but the result I am getting is 'string1,string2,string3,string4' and what I am after is that when is pushed into the array, each string must be a different element:
content ['string1','string2','string3','string4']
only then it will render properly in my views by looping the array. I want to achieve this by javaScript or jQuery only, please.
UPDATE: this is how I am rendering in my view
<ul>
<% var i; for (i = 0; i < course.content.length; i++) { %>
<li><i class="fas fa-check"></i> <%= course.content %></li>
<% }; %>
</ul>
UPDATE: this is my route where this POST request is being done
router.post("/", middleware.isLoggedIn, function(req, res) {
Course.create(req.body.course, function(err, course) {
if (err) {
req.flash("error", err.message);
return res.redirect("back");
}
res.redirect("/courses/" + course.id);
});
});
SOLVED! by using split on the server side like this:
router.post("/", middleware.isLoggedIn, function(req, res) {
Course.create(req.body.course, function(err, course) {
if (err) {
req.flash("error", err.message);
return res.redirect("back");
} else {
var content = req.body.course.content.toString().split(",");
course.content = content;
course.save();
console.log(course.content);
res.redirect("/courses/" + course.id);
}
});
});
Here is another solution in javaScript using function beforesubmit() by #garry man see below.
codepen
Long way
Otherwise there's one work around is as many tags you enter, that much input elements you should generate.
For e.g. my input tags are foo,bar then 2 input tags will be generated like
Note square brackets below
<input id="hiddenInput" type="hidden" name="course[content][]" required>
<input id="hiddenInput" type="hidden" name="course[content][]" required>
This is long way.
Another way
If you submit form via AJAX, then you can manipulate data before submitting and convert string into array with the use of .split(',').
Another way (Server side)
Split string by , on server side.
Okay so the problem is that you are submitting a form containing a single input which can only contain string values.
HTML Form practice is to have a single input for each array element to be posted, like:
<input name="course[content]"/> //value 1
<input name="course[content]"/> //value 2
<input name="course[content]"/> //value 3
So, in order to achieve that, before submit, you can call this function that generates those elements for you:
function beforesubmit(){
let submitVal = document.getElementById('hiddenInput');
let values = submitVal.value.split(',');
//let's get the container of the params passed to post
let paramsContainer = submitVal.parentElement;
// remove the param containting the string with commas as we're generating new ones
paramsContainer.removeChild(submitVal);
for(let i =0; i<values.length;i++){
//for each value, add a submit param containing each value
let tmp = document.createElement('input');
tmp.setAttribute('type','hidden');
tmp.setAttribute('name','course[content]');
tmp.setAttribute('value',values[i]);
paramsContainer.appendChild(tmp);
}
document.getElementsByTagName('form')[0].submit();
}
in order to call this function, replace your submit input with this:
<input type="button" value="submit" onclick="beforesubmit()">
Using this code you can already see the POST request difference between before and after. In your codepen it sends a single parameter, while with this snippet of code you are going to send an array of course['content'].
Now it's all up to how you are going retrieve data server side, you should be retrieving the course['content'] param as an array.

How to remove html tags from text in angular 2

I am working with rss feed and got rss feed from my server so i am sending stringfy data but when i bind this in my angular 2 application it shows text with html tags so how we can remove this tags. I just want to show text only.
Here is server code:
exports.newspage=function(req,resp){
db.executeSql("select header,text,teaser from news_d",function(data,err){
if(err){
resp.writeHead(200,{"Content-Type":"text/html"});
resp.write("<html><head><title>500</title></head></html>");
}
else{
resp.writeHead(200,{"Content-Type":"x-application/json"});
resp.write(JSON.stringify(data));
}
resp.end();
});
};
app.get('/newspage', function(req, resp) {
emp.newspage(req,resp);
});
service.ts:
gettagesnews(){
let headers = new Headers();
headers.append('x-access-token',this.token);
var options = new RequestOptions({headers: headers});
return this.http.get('http://services.com:9000/newspage/',options).map((res:Response) => res.json())
.catch((error:any) => Observable.throw(error.json().error || 'Server error'));
}
news.ts:
tagesnews:Array<TagesnewsList>;
this.newsauth.gettagesnews().subscribe((dailynews)=>{
this.tagesnews=dailynews;
});
html:
<div *ngFor="let daily of tagesnews">
<span style="font-size: 13px">{{daily.text}}</span> </button>
</div>
i got response with some like this:
sample text
You just need to bind html:
<div *ngFor="let daily of tagesnews">
<span style="font-size: 13px" [innerHTML]="daily.text"></span>
</div>
All of the [innerHTML] answers have the content of the HTML actually rendered... so images are loaded, etc. well if you don't want that, and just the text... you can use a conversion method like this:
stripHtml(html: string) {
var div = document.createElement("DIV");
div.innerHTML = html;
let cleanText = div.innerText;
div = null; // prevent mem leaks
return cleanText;
}
Use replace method with regx to remove the unwanted patterns from the content.
content.replace(/<[^>]*>/g, '\n')
There are two ways to handle it.
1) use the innerHTML tag in your html file
like this =
<div>
<pre [innerHTML]="description"></pre>
</div>
here, description is field which hold the data with html tags(<div>hi<br></br></div>)
2) Second way is that convert your html tags data in plain string then bind with respective form control.
like :- formData['description'] = formData['description'].replace(/<[^>]*>/g, '');

Update and delete buttons using node.js

I am very new to programming, it might sound stupid but can anyone of you please help me out. I am designing a cart page using node.js which adds each item at once. There are two buttons update and delete, everything is working fine except these buttons. Can anyone help me out to make these buttons working.
Thank you
Here is my code.
cart.js
var express = require('express');
var router = express.Router();
router.all('/', function (req, res, next) {
var cartTgt = [];
if (req.session.cart !== undefined) {
cartTgt = req.session.cart;
}
res.render('cart', {title: 'Your Cart', cart: cartTgt,message: 'Successfully Added'});
});
module.exports = router;
order.js
var express = require('express');
var router = express.Router();
router.all('/', function (req, res, next) {
var message = '';
if (req.method === 'POST') {
if (req.session.cart === undefined) {
req.session.cart = [];
}
var item = {};
item.itemname = req.body.itemname;
item.quantity = req.body.quantity;
req.session.cart.push(item);
console.log(req.session.cart);
}
res.render('order', {title: 'Order Form', message: 'The item has been added to the cart!'});
});
module.exports = router;
cart.jade
html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
body
header
h1= title
hr
section
form(method='post' action='/cart')
table
thead
tr
th Item Name
th Quantity
th Update
th Delete
tbody
each item in cart
tr
td #{item.itemname}
td #{item.quantity}
td: input(type='submit',value='Update')
td: form(method='post' action='/cart')
input(type='submit',value='Delete')
br
p= message
order.jade
html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
body
h1= title
hr
form(method='POST', action='/order')
label Item Name:
br
input(type='text', name='itemname')
br
label Quantity:
br
input(type='text', name='quantity')
br
input(type='submit')
br
a(href='/') Home Page
br
a(href='/cart') Cart Page
hr
p= message
Solution:
You are using nested form to update and delete, besides you are not sending which item quantity is to be updated or deleted. Thus, better option is to eliminate the nested forms and use simple anchor tags, in which you can send a GET request with itemname in the query string and on cart.js retrieve the itemname and update the req.session.cart as you need.
Cart.jade
td: a(href='http://yourwesite/cart/update?item='+item.itemname) Update
td: a(href='http://yourwesite/cart/delete?item='+item.itemname) Delete
Cart.Js
app.get('/update',function(req,res,next){
// get the itemname from querystring using req.query.itemname
// and perform operations in the req.session.cart array
var temp = req.session.cart.map(function(value,index,array){
if(value.itemname === req.query.itemname){
value.quantity +=1;
}
return value;
});
req.session.cart = temp;
res.render('cart', {title: 'Your Cart', cart: req.session.cart, message: 'Successfully Added'});
});
app.get('/delete',function(req,res,next){
// get the itemname from querystring using req.query.itemname
// and perform operations in the req.session.cart array
var temp = req.session.cart.filter(function(value,index,array){
if(value.itemname === req.query.itemname){
// remove the item from the cart array
return false;
}
return true;
});
req.session.cart = temp;
res.render('cart', {title: 'Your Cart', cart: req.session.cart, message: 'Successfully Added'});
});
Notes:
If you have to use POST request then you have to have two separate forms. But you can achieve it using GET request also thus a tags are favorable for that.
In both cases:
The form should be there for each item, not for the whole table. Considering there are no more problems, only one item would be changed regardless of which "Update" button was pressed.
You're also not sending the item name to the server when submitting the form. When using HTML forms, everything you want to send in the request must be inside an <input> tag (or you use XMLHttpRequest and specify what you want manually). I suggest adding an hidden field to store it like this:
input(type='hidden' name='itemname' value='#{item.itemname}')
Also, you cannot nest HTML forms, so the two used in the table must be separated. And finally, are you sure everything worked as expected? The quantity cannot be edited without using an input tag for it in the cart page.
I suggest you change your code (inside cart.jade) as such:
html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
body
header
h1= title
hr
section
//form(method='post' action='/cart') -> Moved below
table
thead
tr
th Item Name
th Quantity
// No th Update, explained why below
th Delete
tbody
each item in cart
tr
td #{item.itemname}
// The whole form needs to be inside a single <td> tag, so the quantity and update columns are merged together
td
form(method='post' action='/cart')
// Send the item's name
input(type='hidden' name='itemname' value='#{item.itemname}')
// Expose the quantity as a editable text box (in an input so it gets sent)
input(type='number' name='quantity' value='#{item.quantity}')
input(type='submit' value='Update')
// The delete button form, completely contained in the <td> tag
td
form(method='post' action='/cart')
// Send the item's name
input(type='hidden' name='itemname' value='#{item.itemname}')
input(type='submit' value='Delete')
br
p= message
To avoid the duplicate hidden inputs you could try sending requests without forms: with XMLHttpRequest. I advise against using it directly so try a library like qwest or jQuery.

passing data between server and client (node.js + mongodb)

I'm working with node.js express and mongodb, I have a input data from client, I need to pass the data to server look for its property and send to the client in another page.
Now I have problem with req.body.age that suppossed to get the data from client's input and use find() to get its appropriate property.
Server side code:
functions are routed in another .js file
exports.find_user = function(req, res) {
res.render('find_user.jade');
};
exports.user = function(req, res){
member = new memberModel();
member.desc.age = req.body.age; //problem
console.log(req.body.age); //undefined
memberModel.find({desc: {age: '7'}}, function(err, docs){
res.render('user.jade', { members: docs });
console.log(docs);
});
};
memberModel.find({desc: {age: '7'}} just hardcode picking up user with age 7 (works)
client side code (jade):
page for data input:
find_user.jade
form(action='/', method='post')
fieldset
lable(for="age") Find user by age:
input(type="text", size="30", name="age", required="required")
input(type='button', value='Find', onclick='location.href=\'find_user/user/\'')
page for data output with its property:
user.jade
tr
th Name
th Age
tbody
- members.forEach(function(member){
tr
td= member['name']
td= member['desc']
- });
You are not submitting your data in find_user.jade file when the user clicks the button. Instead, the client is only redirected to another page.
This is how your find_user.jade file should look like:
form(action='find_user/user/', method='post')
fieldset
label(for="age") Find user by age:
input(type="text", size="30", name="age", required="required")
input(type='submit', value='Find', name="submit")

Categories