KeystoneJS post request does not work - javascript

This is my view
form.contact-form(method="post").col-md-12
input(type='hidden', name='action', value='notes.edit' + data.post.id)
.form-group.col-md-12
.form-group.col-md-12
label.text-center Title
input.form-control.input-box(type='text', name='title', value=data.post.title, placeholder='Title' required)
.form-group.col-md-12
label.text-center Content *
.row
.col-md-6
input.form-control.input-box(type='text', name='briefcontent', value=data.post.content.brief, placeholder='brief content')
.col-md-6
input.form-control.input-box(type='text', name='extendedcontent', value=data.post.content.extended placeholder='extended content')
button(type='submit').btn.btn-success Edit Notes
form.contact-form(method="post").col-md-12
This is my post route
view.on('post', { action: 'notes.edit'}, function(next) {
console.log('edit notes')
res.redirect('/')
});
This is my route bindings
// Setup Route Bindings
exports = module.exports = function (app) {
// Views
app.all('/', routes.views.index);
app.get('/blog/:category?', routes.views.blog);
app.get('/blog/post/:post', routes.views.post);
app.get('/gallery', routes.views.gallery);
app.get('/registration', routes.views.registration);
app.post('/registration', routes.views.registration);
app.all('/signin', routes.views.signin);
app.all('/signout', routes.views.signout);
app.all('/contact', routes.views.contact);
app.all('/addnotes', routes.views.addnotes);
app.all('/editnotes/:post', routes.views.editnotes);
app.all('/editnotes', routes.views.editnotes);
The post request does not seem to work at all. I try console.log for the post request but in does not appear in terminal.

You're appending the data.post.id to the value property of your input. Thus, the input value changes to be something that isn't notes.edit. Your POST route is expecting a request with an action value of only notes.edit, therefore the POST request isn't being handled by that route.
In your Pug template:
input(type='hidden', name='action', value='notes.edit')
EDIT:
You have a second form within your form. That may have something to do with it as well. Try removing it.

Related

Proper display of user editing form (CRUD model) with checkbox

I'm making a simple CRUD model with input checkbox. I have no problems on server side, everything is fine. I use NodeJS +MongoDB. But I have problem in editing existing user. When I edit an existing user with a checked checkbox( I get JSON object with parameter checked=true ) how should I display it using JS? This is part of my users.js file in /routes/ folder
var express = require('express');
var router = express.Router();
var User = require('../../models/User');
var rest = require('restler');
router.get('/adduser', function(req, res){
var user = new User();
user.contacts.push({phone: '', email: ''});
rest.get('http://localhost:3000/api/adduser').on('complete', function(data) {
res.render('users/add', { title: 'Add New Users' , n: user});
});
});
And this is views/users/fields.jade part of file for better understanding:
.form-group
label.col-sm-2.control-label(for='email') E-mail:
.col-sm-10
input(type="email", placeholder="email", name="email", value = n.contacts[0].email,required)
.form-group
.col-sm-offset-2.col-sm-10
input#enabled(type="checkbox",style='text-align: center; vertical-align: middle;',placeholder="", name="enabled", value = n.enabled)
| Enable user
So my problem is that I don't understand how I should display that checkbox is really checked when loading existing user.
If user is checked attribute n.enabled=true and if not n.enabled=false. So if user is checked on load of that user I need the input filed to be checked.
I've tried it to do the following way, but it wrote me that n wasn't defined...and I don't know how to pass n as the parameter for that function:
$(document).ready(function(){
if(n.enabled=="true"){$("enabled").toggle(this.checked);}
});
In fields.jade, change value = n.enabled to checked = (n.enabled ? 'checked' : '')
Use # for id-selectors and use n.enabled directly to hide or show your element like,
$("#enabled").toggle(n.enabled);
//-^ prepend # before id selectors
toggle() will show/hide your element, To check uncheck use the prop() like
$(document).ready(function(){
$("#enabled").prop("checked",n.enabled);
});

Angularjs: HTML DOM is not updated

I've an inherited project writed in django 1.4 and I've no time to update it to another version of django.
I'm introducing angularjs in that project being newbie with it.
So, I've a HTML filled with data from the database (very simplified code):
<div ng-app="myApp" ng-controller="commentController">
<input placeholder="say something!" type="text">
<button class="btn" ng-click="sendComment()" >
<li ng-repeat="comment in comments" id="aportacion{{comment.pk}}">
{{comment.username}} - {{comment.text}}
</li>
</div>
And angularjs app (simplified) to fill the table with comments:
var app = angular.module("myApp", []);
app.controller("commentController",function ($scope) {
$scope.comments = [];
// this is generated dinamically with django from db data on page generation;
$scope.comments[$scope.comments.length] = {"username":"inigod", "text":"this is sparta"};
$scope.comments[$scope.comments.length] = {"username":"another guy", "text":"this is NOT sparta"};
.......
};
});
This works great, it builds all the comments ok, nice.
Now I've a textbox to add new comment and want to send via ajax the new comment to db and with the response json add a new comment in the top of the comments in html.
I've tried modificating the angularjs code to this:
app.controller("commentController",function ($scope) {
$scope.comments = [];
// this is generated dinamically with django from db data on page generation;
$scope.comments[$scope.comments] = {"username":"inigod", "text":"this is sparta"};
$scope.comments[$scope.comments] = {"username":"another guy", "text":"this is NOT sparta"};
$scope.sendComment = function(){
Dajaxice.kolokvoweb.post_comment($scope.comment_callback, {'thread':'{{thread.pk}}',
'type': 0,
'text': $('#comment').val(),
});
}
$scope.comment_callback = function (data){
if (data.result){
data["image"]= "/img/comment-placeholder.png";
//data["$$hashKey"] = "003";
alert("adding element" +$scope.aportaciones.length);
$scope.comments.push(data);
alert("added element" +$scope.aportaciones.length);
}
}
So I run this and I get two alert, one saying "adding element n" and the next "added element n+1" so it appears to reach to $scope.comment_callback an push the data to the array but the DOM is not updated and I cannot see the inserted comment in the page.
I must be something wrong but cannot find what...
I've see the response from ajax and is the same kind of JSON but withouth the $$haskey key.
PD: received data from the ajax service is:
{"username":"inigo","texto":"ggggggggggggggggggggggg","date":"now","result":true,"pk":74,"foto":"/img/agora-placeholder.png"}
The one getted when loading page for that comment (and which is well shown in the page) is:
{"pk":"74","texto":"ggggggggggggggggggggggg","username":"inigo","date":"10/11/14","foto":"/img/agora-placeholder.png"}
You have to wrap the content of comment_callback in a $scope.$apply method to notify about $scope changes within async callbacks:
$scope.comment_callback = function (data){
if (data.result){
$scope.$apply(function() {
data["image"]= "/img/comment-placeholder.png";
$scope.comments.push(data);
});
}
}

Meteor easy search and iron-router

I'm using this easy serach for my project https://github.com/matteodem/meteor-easy-search
my search Index
EasySearch.createSearchIndex('searchIndex', {
'collection' : blog,
'field' : ['title', 'tags'],
'limit' : 20,
"use":"mongo-db",
'query' : function (searchString) {
// Default query that will be used for searching
var query = EasySearch.getSearcher(this.use).defaultQuery(this, searchString);
return query;
}
});
and now I have search box and when User enters something and click on enter I want to route to search page
this.route("search",{
path:'/search/:slug',
waitOn:function(){
//here I want the search data to be sent to search page
var query=this.params.slug;
EasySearch.search('searchIndex', query, function (err, data) {
console.log(data);
});
},
data:function(){
}
});
In this router I want the searchIndex data to be sent to search page, how to do this
my click event
'submit .search':function(e){
e.preventDefault();
var quer=$("#query").val();
// Router.go('search');
}
UPDATE
My main question is in the router waiton function how we get the data in callback and send it to the search page?
In your click event handler, you have commented out the line: Router.go('search').
If you write
Router.go('search', {slug: quer})
That would route you to the search page with the query data collected from the page, if that is what you want.

Why do I receive undefined value after reloading page in Meteor?

So I have the following form:
template(name='editUser')
.row
.col-md-4.col-md-offset-4
.page-header
h1 Edit user
form#edit-user-form
.form-group
label(for='name') Name
input#user-name.form-control(type='text' placeholder='Name' value='{{user.name}}')
.form-group
label(for='email') E-Mail
input#user-email.form-control(type='text' placeholder='E-Mail' value='{{getEmail user}}')
button.btn.btn-primary(type='submit') Update
the following handlebars.js-Helper:
Handlebars.registerHelper('getEmail', function (user) {
if (user.emails && user.emails[0] && user.emails[0].address)
return user.emails[0].address;
return '';
});
and the following iron-Router code:
EditUserController = RouteController.extend({
template: 'editUser',
waitOn: function () {
return Meteor.subscribe('user', this.params._id);
},
data: function () {
return {
user: Meteor.users.findOne( { _id: this.params._id } )
};
}
});
If I run my application and click on the link to the edit-User-Form I can see the E-Mail Address. But if I change my code and Meteor automatically refreshes the page, the E-Mail-Field is empty and the console says, that it can't fetch the value of undefined.
If I use the same form, but with a with-Helper, the E-Mail is displayed even if Meteor automatically refreshes the page:
template(name='editUser')
.row
.col-md-4.col-md-offset-4
.page-header
h1 Edit user
form#edit-user-form
with user
.form-group
label(for='name') Name
input#user-name.form-control(type='text' placeholder='Name' value='{{name}}')
.form-group
label(for='email') E-Mail
input#user-email.form-control(type='text' placeholder='E-Mail' value='{{getEmail this}}')
button.btn.btn-primary(type='submit') Update
Why is this so? And should I always use the with-Helper if I get single Results (only one Result to display)?
Thanks in advance!
Replace Meteor.users.findOne with Meteor.users.find.
When findOne doesn’t find anything, it returns undefined which causes your error; when find doesn’t find anything, it returns an empty cursor which Meteor knows what to do with. Essentially all you were doing by adding with was to cause Meteor to check if the value was undefined, but that check isn’t necessary for a cursor, empty or otherwise.

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