model undefined on page reload - node.js

I'm trying example from this site. It works fine. But if i separate views,models,routers into separate file it gives me a problem. There is 3 views. WineList view, WineListItemView and winedetails view. WineList view takes collection of wine models as model and winelistItem and winedetails view takes wine as a model.
Router's code is like this
var app = app || {};
app.AppRouter = Backbone.Router.extend({
routes:{
"":"list",
"wines/:id":"wineDetails"
},
initialize:function () {
$('#header').html(new app.HeaderView().render().el);
},
list:function () {
this.wineList = new app.WineCollection();
this.wineListView = new app.WineListView({model:this.wineList});
this.wineList.fetch();
$('#sidebar').html(this.wineListView.render().el);
},
wineDetails:function (id) {
if(this.wineList == undefined)
{
this.wineList = new app.WineCollection();
this.wineListView = new app.WineListView({model:this.wineList});
this.wineList.fetch();
$('#sidebar').html(this.wineListView.render().el);
}
this.wine = this.wineList.get(id);
if (app.router.wineView) app.router.wineView.close();
this.wineView = new app.WineView({model:this.wine});
$('#content').html(this.wineView.render().el);
}
});
On page load it fetches models from server and displays list of wines in sidebar div of page. When i click on particular wine item its details will be displayed in content div of page. That all works fine. But when i reload that page which now contains details of particular,wine model of Winedetails view gives undefined .
I'm intializing the router on main page like this
app.js
var app = app || {};
$(function() {
})
app.router = new app.AppRouter();
Backbone.history.start();
index.html
<!DOCTYPE HTML>
<html>
<head>
<title>Backbone Cellar</title>
<link rel="stylesheet" href="../css/styles.css" />
</head>
<body>
<div id="header"><span class="title">Backbone Cellar</span></div>
<div id="sidebar"></div>
<div id="content">
<h2>Welcome to Backbone Cellar</h2>
<p>
This is a sample application part of of three-part tutorial showing how to build a CRUD application with Backbone.js.
</p>
</div>
<div>
Next page
</div>
<!-- Templates -->
<script type="text/template" id="tpl-header">
<span class="title">Backbone Cellar</span>
<button class="new">New Wine</button>
</script>
<script type="text/template" id="tpl-wine-list-item">
<a href='#wines/<%= id %>'><%= name %></a>
</script>
<script type="text/template" id="tpl-wine-details">
<div class="form-left-col">
<label>Id:</label>
<input type="text" id="wineId" name="id" value="<%= id %>" disabled />
<label>Name:</label>
<input type="text" id="name" name="name" value="<%= name %>" required/>
<label>Grapes:</label>
<input type="text" id="grapes" name="grapes" value="<%= grapes %>"/>
<label>Country:</label>
<input type="text" id="country" name="country" value="<%= country %>"/>
<label>Region:</label>
<input type="text" id="region" name="region" value="<%= region %>"/>
<label>Year:</label>
<input type="text" id="year" name="year" value="<%= year %>"/>
<button class="save">Save</button>
<button class="delete">Delete</button>
</div>
<div class="form-right-col">
<img height="300" src="../pics/<%= picture %>"/>
<label>Notes:</label>
<textarea id="description" name="description"><%= description %></textarea>
</div>
</script>
<!-- JavaScript -->
<script src="js/lib/jquery.min.js"></script>
<script src="js/lib/underscore.js"></script>
<script src="js/lib/backbone.js"></script>
<script src="js/models/WineModel.js"></script>
<script src="js/collections/WineListCollection.js"></script>
<script src="js/Views/WineListView.js"></script>
<script src="js/Views/WineListItemView.js"></script>
<script src="js/Views/WineDetailsView.js"></script>
<script src="js/Views/HeaderView.js"></script>
<script src="js/routers/routers.js"></script>
<script src="js/app.js"></script>
</body>
</html>
I'm new to this backbone technology. please tell me what am i missing

this.wineList.fetch();
fires an asynchronous request to your server, which means that the content will arrive (or not) at some point after executing this line, but your application execution continues whether the response arrived or not. On page reload (assume you have wines/:id in the URL) first you have to fetch the complete list of wines before accessing any particular wine from the collection.
You have to wait until is download the collection, and access the wine with id, after this request is finished.
So after initiating the request continue your application logic in the success callback:
this.wineList.fetch({
success: function(model) {
...
this.wine = model.get(id);
...
}
});

Related

Get the status of toggle button via req.body when multiple buttons are generated dynamically and the text on the button will change

I'm currently trying to implement a form which has multiple toggle button.
For example, something like this:
The number of the options will be different each time.
For example, if the title is Chef's pizza, the option may be "Add cheese", "Add extra tomato", and "Add black olive". There can be a large number of options (like 100s) depending on the item.
The text of the toggle button will be changed from "Select" to "Selected" or vice versa.
So far, I was able to implement toggle buttons with changing the text on it. However, I'm currently facing challenge how I can get the status of the toggle buttons via req.body.
I'm using node + express + Bootstrap 5 + EJS + mongoDB.
JQuery is also used to toggle the text on the switch.
I included console.log(req.body) to the controllers js file which is called from route js file but the result is as the following:
req.body
{ post: { comment: 'Please remove tomato' } }
As you can see, it only includes the input from text form("Please remove tomato"). How can I get the status of each toggle button (selected/unselected) via this req.body so I can use them in the next process(store those to mongoDB)?
As the number of the options are different (and can be large) for each item, I'm thinking to generate the toggle buttons with something like name="<%= optionIdFromMongoDB %>" for the name field of the form tag of for each options and was wondering how I can collect the result via req.body for each options.
Following is the code.
[selectItem.ejs]
<head>
<script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
<script type="text/javascript" src="/javascripts/external.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bs-custom-file-input/dist/bs-custom-file-input.js"></script>
</head>
<body>
<div class="row">
<h1 class="text-center">Select Option</h1>
<div class="col-md-6 offset-md-3">
<form id="sub-form" action="/posts/<%= order._id %>/review" method="POST">
<div class="mb-3">
<label class="form-label" for="title">Title</label>
<h3>Chef's salad</h3>
</div>
Add cheese
<span id="buttonsend" class="notsosmall pink button">
<input form="sub-form" type="checkbox" class="btn-check" id="btn-check" autocomplete="off" name="post[toggle]">
<span class="btn btn-primary" for="btn-check" name="post[toggleA]" value="unselected">Select</span>
<span class="btn btn-primary" for="btn-check" style="display:none" name="post[toggle]" value="selected">Selected</span>
</span>
<br>
Add bacon
<span id="buttonsend" class="notsosmall pink button">
<input form="sub-form" type="checkbox" class="btn-check" id="btn-check" autocomplete="off" name="post[toggle]">
<span class="btn btn-primary" for="btn-check" name="post[toggleB]" value="unselected">Select</span>
<span class="btn btn-primary" for="btn-check" style="display:none" name="post[toggle]" value="selected">Selected</span>
</span>
<div class="mb-3">
<button class="btn btn-lg btn-primary font-weight-bold border-white text-white">Post</button>
</div>
</form>
</div>
</div>
</body>
[external.js (used to toggle the text on the button)]
$(document).ready(function(){
$('span#buttonsend').click(function(){
$('span',this).toggle();
});
});
[/routes/posts.js]
const express = require('express');
const router = express.Router();
const posts = require('../controllers/posts')
router.route('/posts/:id/review')
.post(isLoggedIn, catchAsync(posts.review))
[/controllers/posts.js]
module.exports.review = async (req, res, next) => {
console.log("req.body")
console.log(req.body)
// some more codes here
res.render('posts/review')
}
Thank you,

Escape script to hide/reveal textarea

I need to make my button click to reveal the textarea so the user can choose between uploading either an image or a text message. I can see the hidden/visible element kicking in when I run the page but it doesn't remain in the new state. It immediately reverts back to whatever it was originally set as.
I'm guessing that I'm not escaping the script properly. Any thoughts?
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Site Media</title>
</head>
<header id="headtitle">
</header>
<body>
<div id="PostContainer"><br>
<textarea id="textmessage" rows="7" cols="40" maxlength="280" placeholder="Enter message here..." width="100%" style="visibility: hidden"></textarea><br>
<form class="UploadButtonContainer">
<button id="textbutton" type="submit" name="submit" onclick="revealinput()" style="display: none;"></button>
<label for="textbutton" style="cursor: pointer;" ><img src="Images/AYE PING.png" width="30%" alt="Choose Text Post" >
</label>
</form>
<script>
function revealinput() {
var x = document.getElementById("textmessage");
if (x.style.visibility === "hidden") {
x.style.visibility = "visible";
} else {
x.style.visibility = "hidden";
}
}
</script>
</div>
</body>
</html>
The script didn't like the button being inside a tag. I changed it to a tag and it works now.

Autofill checkbox using string query in url but specifying a fieldset

I'm trying to get filtered data from a webform more quickly. Basically I want to use URL input to specify a date and to precheck a checkbox. I'm getting stuck with how to specify the check box as I'm not sure what the value should be.
<form action="/xxx/yyy" class="form-inline d-flex justify-content-end" method="get"> <div class="input-group input-group-lg mb-2">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-calendar"></i></span>
</div>
<input type="text" name="from" value="" class="form-control datetimepicker-input" id="datetimepicker7" data-toggle="datetimepicker" data-target="#datetimepicker7" autocomplete="false">
<div class="input-group-append">
<button type="submit" class="btn btn-dark"><i class="fas fa-arrow-right"></i></button>
</div>
</div>
</form>
####snip and skip to the part of the form I wish to pre-check####
<fieldset id="departureGatewayFilters">
<div class="form-check">
<input class="form-check-input" type="checkbox" value="AMS" id="departureGatewayCheck_AMS">
<label class="form-check-label" for="departureGatewayCheck_AMS">
AMS
</label>
</div>
So far I'm using URL string: /xxx/yyy?from=2020-03-05 - what would I need next to pre-check the checkbox as well?
Thanks in advance!
Clare
Getting your checkbox checked and also getting value of the checkbox just through URL string is little bit troublesome. But you can try this :
You can assign unique name to the checkbox.
<input class="form-check-input" type="checkbox" name="checkbox_1" id="departureGatewayCheck_AMS">
And then what you can do is pass the value of checkbox through URL string. For example :
/xxx/yyy?from=2020-03-05&checkbox_1=test.
Now, using javascript you can parse URL strings and get your search params, compare it and get your checkbox checked.
<script lang="javascript">
var url_string = window.location.href ; //gets current URL
var url = new URL(url_string); // instantiate string as URL object
var c = url.searchParams.get("checkbox_1"); //get the params
if(c == "test") {
document.getElementById("departureGatewayCheck_AMS").checked = true; //checks your checkbox
}
</script>
Hope it helps ! Have a good day!
I think all you need to do is add a (checked="true") argument to your input tag your code should look like this then:
<div class="form-check">
<input class="form-check-input" checked="true" type="checkbox" value="AMS" id="departureGatewayCheck_AMS">
<label class="form-check-label" for="departureGatewayCheck_AMS">
AMS
</label>
</div>
Hope this helps
If you want to make the checkbox departureGatewayCheck_AMS checked by default, it is sufficient to edit its code like this:
<input class="form-check-input" type="checkbox" value="AMS" name="departureGatewayCheck_AMS" id="departureGatewayCheck_AMS" checked> AMS
If the checkbox is selected, since its "value" attribute is "AMS",your url (if you submit the form via GET) would be something like:
/xxx/yyy?from=2020-03-05&departureGatewayCheck_AMS=AMS
Complete solution for your requirement:-
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/css/bootstrap-datetimepicker.min.css" integrity="sha256-yMjaV542P+q1RnH6XByCPDfUFhmOafWbeLPmqKh11zo=" crossorigin="anonymous" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
<div class="container">
<form class="form-inline d-flex justify-content-end" method="get"> <div class="input-group input-group-lg mb-2">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-calendar"></i></span>
</div>
<input type="text" name="from" value="" class="form-control datetimepicker-input" id="datetimepicker7" autocomplete="false">
<div class="input-group-append">
<button type="submit" class="btn btn-dark"><i class="fas fa-arrow-right"></i>
</button>
</div>
</div>
<fieldset id="departureGatewayFilters">
<div class="form-check">
<input class="form-check-input" name="checkname" type="checkbox" value="AMS" id="departureGatewayCheck_AMS">
<label class="form-check-label" for="departureGatewayCheck_AMS">
AMS
</label>
</div>
</fieldset>
</form>
</div>
</body>
<script type="text/javascript">
$(function () {
var url_string = "https://www.example.com/page?from=2020-12-12&checkname=1";//window.location.href ; //gets current URL
var url = new URL(url_string); // instantiate string as URL object
var date=url.searchParams.get("from");
var check = url.searchParams.get("checkname"); //get the params
alert(date);
alert(check);
if(check) {
$( "#departureGatewayCheck_AMS" ).prop( "checked", true );
}
$('.datetimepicker-input').datetimepicker({
format: 'YYYY-MM-DD',
defaultDate: date,
});
});
</script>

getting not a buffer error with express js node

I am following module p-11(authentication, hashing, curl,etc) and want to do the create user but it's somehow not working.
The problem is that as soon as I am clicking on the submit button
I am getting the not a buffer error.
not sure what's wrong.
I keep getting the error : TypeError: Not a buffer
I have already required body-parser and crypto.
here's the related code in server.js:
function hash(input,salt){
//how to create hash
var hashed = crypto.pbkdf2Sync(input,salt, 10000, 512, 'sha512');
return ['pbkdf2Sync',salt,hashed.toString('hex')].join('$');
}
app.post('/create-user',function(req,res){
//take username and password as input and create entry in user table
var username = req.body.username;
var password = req.body.password;
console.log(username);
var salt= crypto.randomBytes(128).toString('hex');
var dbString = hash(password,salt);
pool.query('INSERT INTO "user"(username,password) VALUES($1,$2)',[username,dbString],function(err,result){
if(err){
res.status(500).send(err.toString());
}else{
res.send('user succesfully created'+username);
}
});
});
app.get('/hash/:input',function(req,res){
var hashString = hash(req.params.input,'this-is-some-random-string');
res.send(hashString);
});
And here's the related code in main.js
var submitButton = document.getElementById('submit_btn');
submitButton.onclick = function(){
var request = new XMLHttpRequest();
request.onreadystatechange=function(){
if(request.readyState===XMLHttpRequest.DONE && request.status ===200){
var data = JSON.parse(request.responseText);
console.log(data);
}
};
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
request.open('POST','http://localhost:8080/create-user',true);
request.send(JSON.stringify({username:username,password:password}));
};
Here's the error message I am getting
TypeError: Not a buffer
at TypeError (native)
at pbkdf2 (crypto.js:562:20)
at Object.exports.pbkdf2Sync (crypto.js:553:10)
at hash (D:\imadtw\server.js:119:23)
at D:\imadtw\server.js:129:18
at Layer.handle [as handle_request] (D:\imadtw\node_modules\express\lib\router\layer.js:95:5)
at next (D:\imadtw\node_modules\express\lib\router\route.js:131:13)
at Route.dispatch (D:\imadtw\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (D:\imadtw\node_modules\express\lib\router\layer.js:95:5)
at D:\imadtw\node_modules\express\lib\router\index.js:277:22
at Function.process_params (D:\imadtw\node_modules\express\lib\router\index.js:330:12)
at next (D:\imadtw\node_modules\express\lib\router\index.js:271:10)
at jsonParser (D:\imadtw\node_modules\body-parser\lib\types\json.js:112:7)
at Layer.handle [as handle_request] (D:\imadtw\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (D:\imadtw\node_modules\express\lib\router\index.js:312:13)
at D:\imadtw\node_modules\express\lib\router\index.js:280:7
EDIT: I just tried something.
the process works okay, when I hard code the values of username and password (just as an experiment), but it doesnt work when I try to get the values of username and password using req.body
seems like getting the values from body is the hard part here.
Here's the html of the page I want input values from
<!doctype html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- Fontawesome library -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="/ui/profile.css">
<script type="text/javascript" src="/ui/main.js" ></script>
</head>
<body>
<!--Navbar Begins -->
<nav class="navbar navbar-fixed-top scrolltop" id="navigation">
<div class="container">
<!-- navbar header begins -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse">
<span class="sr-only">Toggle Navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Faraz Ahmed</a>
</div>
<!-- navbar header ends -->
<!-- div collapse begins -->
<div class="collapse navbar-collapse" id="navbar-collapse">
<ul class="nav navbar-nav navbar-right">
<li class="active">About</li>
<li>Portfolio</li>
<li>Contact</li>
</ul>
</div>
<!-- div collapse ends -->
</div>
<!-- container ends -->
</nav>
<!--Navbar ends -->
<div class="container-fluid">
<div class="row" id="fullBody">
<div class=" col-md-12 col-sm-12 col-xs-12" id="column-main">
<div id="aboutme" class="about">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12">
<div id="img"><img class="img-responsive" src="http://res.cloudinary.com/whizzy/image/upload/v1454699647/faraz_qwdqrx.jpg" alt=""></div>
<!-- <hr class="hr1"><i class="fa fa-star"></i><hr class="hr2"> -->
<p class="aboutpara scrollz"></br>I am a self taught web developer who has learnt html,css, Javascript,Jquery and bootstrap too. I keep building websites and other apps to practice what I have learnt. This site is responsive. Go ahead and take a look at it in your mobile and see how they adjust to your screen size.</p>
</div>
</div>
</div><!-- aboutme div ends -->
<div class="user">
<p>
<form method="post" action="/create-user" >
<input type="text" id="username" placeholder="username">
<input type="password" id="password" name="password">
<input type="submit" id="submit_btn" value="Submit" class="btn btn-warning">
</form>
</p>
<ul id="namelist">
</ul>
</div><!-- requestz div ends -->
<div id='twitterDiv' class="row">
<div class="col-lg-12 col-md-12 col-sm-12">
<h3>Tweets Here</h3>
<input type="text" id="tweetSearch" placeholder="enter keyword to search for"></input>
<button id="tweetButton" type="submit">Submit</button>
<p id="tweetz">tweets appear here</p>
</div><!--column ends -->
</div><!--row ends -->
</div><!--2nd column ends -->
</div><!-- main row ends -->
</div><!-- container-fluid div ends -->
</body>
</html>
Make sure you're setting the correct body content type:
request.open('POST','http://localhost:8080/create-user',true);
request.setRequestHeader('content-type', 'application/json');
request.send(JSON.stringify({username:username,password:password}));
According to your html, you're not setting a name attribute for the username field. This means the field won't be sent to the server when the html form is submitted (separately from your XHR).
EDIT: this is probably unrelated to your particular issue with pbkdf2Sync() though since it doesn't consider the username value.

Google chrome passing value of fields in a form

My popup.html:
<!doctype html>
<html>
<head>
<form name="orderform">
First name: <input type="text" name="firstname" /><br />
Last name: <input type="text" name="lastname" />
<INPUT TYPE="button" NAME="button1" Value="Read" onClick="readText(this.form)">
</form>
<!-- JavaScript and HTML must be in separate files for security. -->
<script src="popup.js"></script>
</head>
<body>
</body>
</html>
popup.js
console.log("In");
function readText (form)
{
TestVar =form.firstname.value;
console.log(TestVar);
chrome.tabs.create({"url":"http://www.google.co.in","selected":true}, function(tab){
});
}
Unfortunately the above code does not print the value of a first name. Could someone please tell me what i am doing wrong here.
Your form is in the <head> section; move it in the body
don't use form.field, use the DOM id property in conjunction with document.getElementById().
Use var to define local variables; like this:
First name: <input type="text" id="firstname" /><!-- note the use of id=... -->
<script type="text/javascript">
var TestVar = document.getElementById('firstname').value;
</script>
use alert() for strings and numbers
Here's the full code:
popup.html
<html>
<head>
<script src="popup.js"></script>
</head>
<body>
<form name="orderform">
First name:
<input type="text" name="firstname" id="firstname" />
<br />
Last name:
<input type="text" name="lastname" id="lastname" />
<input type="button" name="button1" value="Read" onclick="readText()">
</form>
</body>
</html>
popup.js
function readText(){
var TestVar = document.getElementById('firstname').value;
console.log(TestVar); alert(TestVar);
chrome.tabs.create({"url":"http://www.google.co.in","selected":true}, function(tab){ });
}

Resources