Event on Keystone JS view not working - javascript

I'm doing an e-commerce site (learning purposes) with KeystoneJS. In the view where I display all the products I want to add a filter for sort the items by price and another one to show the products of only one brand. Two forms are needed but I don't get to submit only one
My products.pug looks like this
.container
form(method='post')
input(type='hidden', name='action', value='products')
button(type='submit').btn.btn-primary Send
And my products.js in routes/views/ looks like this
[...]
// Print a word when submit the form
view.on('post', { action: 'products' }, function(next) {
console.log('POST')
next()
})
// Get all products from db
view.on('init'...)
// Render
view.render('products')
So basically what I want to do is to print POST when I hit the button in the view. Instead of that, I receive a 404 error page. I would really appreciate if you guys can help me

Got it! In /routes/index.js I replaced
app.get('/products', route.views.products);
for
app.all('/products', route.views.products);
I feel dummy but happy.

Related

using sessions to add an edit button for the right user

Lets say I have a lot of reviews on a web page. and I have a req.session.shortId = f43f1. I'm new to sessions but I think that each person that goes to the page will have their own req.session.shortId. (I have this in my schema shortId : {type : String, unique : true, default : shortId.generate}, )
some reviews are made by one person and I want to have those reviews have an edit button. only the person that has the session should be able to see the edit button. I have on the page something like this <div class = "f43f1">Review</div> , <div class = "f43aa">Review</div>. I only want f43f1 to have the button because that is the value of req.session.shortId. I was thinking of doing something like this on the server.
if(req.session.shortId == req.body.shortId){
I really don't know what to do
how would I tell the user's div that he can edit the button
I do stuff like this
res.render("index", {user : user, comp, comp, how do I send out tell the specific div to put the edit button })
}
Truthfully I don't even want the shortId in the div because of security concers. I don't know how developers handle this type of situation
It seems like you would have that shortId stored with your review in the database. Which should make it easy enough to do something like this in your node app:
res.render('index', {shortId: req.session.shortId, review: review});
Then on your ejs template you should be able to conditionally display the button similar to something like this:
<% if (shortId === review.shortId) { %>
<button type="submit">Edit</button>
<% } %>
Sorry if the syntax is a little off here, it's been a while since I've worked with EJS.

How to apply ajax or javascript in opensource php mini cart?

I got this opensource php mini cart from youtube. Now the problem is how to apply it with ajax or javascript? So that everytime I add, remove and delete the items it wont refresh the whole page and will still work whether the javascript is on or off. If javascript is on the cart.php will use javascript and if it is off the cart.php will use php.
here's the code for add, remove and delete items in the cart. To look or download the full source code just click this link: cart php source code
if(isset($_GET['add'])){
// use session to add the product
$quantity = mysql_query('SELECT id, quantity FROM products WHERE id='.mysql_real_escape_string((int)$_GET['add']));
while($quantity_row=mysql_fetch_assoc($quantity)){
//if quantity is not equal in the database quantity
if ($quantity_row['quantity']!=$_SESSION['cart_'.(int)$_GET['add']]){
$_SESSION['cart_'.(int)$_GET['add']]+='1';
}
}
header('Location: '.$page);
}
if(isset($_GET['remove'])){
$_SESSION['cart_'.(int)$_GET['remove']]--;
header('Location: '.$page);
}
if(isset($_GET['delete'])){
$_SESSION['cart_'.(int)$_GET['delete']]='0';
header('Location: '.$page);
}
It is very simple to implement ajax in opencart. you just need to use it's own prebuilt Cart API and use it in your project.
First need to learn URL for Cart Functionalities
1. http:/ /< project location >/index.php?route=checkout/cart/add (with product_id and quantity as parameters)
2. http:/ /< project location >/index.php?route=checkout/cart/remove (with key as parameter which is cart id)
3. http:/ /< project location >/index.php?route=checkout/cart/edit (quantity[key] and value = 'quantity' as parameters
now you can use these code in Ajax requrest, assuming that your using jquery
var cart = {
'add':function(product_id){
$.get('http:/ /< project location >/index.php?route=checkout/cart/add',
{product_id: product_id},
function(data){}
},
};
Like this you can make add, remove, edit and getcart function and you can add these functions to buttons or page load etc.
for example
<button onclick="cart.add('prod_01');> Add to Cart </button>
Please Note
these routes are basic opencart structure so no need to change it, you just have to use these routes in your javascript code to make ajax call and display the result, it's output is in JSON format, so it is very simple and easy to display a cart.
Good Luck

JavaScript/Ajax to Dynamically Update WTForms Select Field

OK. I know this has been tackled many times but I can't find an answer with a useful example of javascript to use.
Say I have this form:
class MyForm(Form):
category = SelectField("Category")
issue = SelectField("Issue")
What I need is for whatever is selected in 'category' at runtime to determine what the user sees in the issue dropdown without a POST of any kind ocurring. I know how to dynamically create the choices in the view from my database query. I even have gone so far as to create a dictionary of "issue choices" based off of category choices.
I just can't for the life of me figure out the javascript I need so that on select of something from the category drop down determines whats in the issue dropdown.
I found the info I needed by looking at the example at Flask jQuery AJAX Example -
- it is a minimal working example, almost a
GIST or a book chapter.
I came up with an example very close to jsbueno's implementation. You can find the Gist here. The .py file is a standalone example.
In your html template use jquery to register an ajax request when you click the select field. If the request is a success the html for the select field gets updated with the new select options (send as a response from the server). Look at the actual HTML generated by the template to see how the select field looks like.
<form action="" method="post" id="selectDevice" name="device">
Nummber of Devices: {{ form.selectAmount(size=1) }}
Select device: {{form.deviceAddress() }}
</form>
<script type="text/javascript" charset="utf-8">
$("#deviceAddress").click(function(){
$.ajax({
url: '/selectform',
type: 'POST',
data: $('#selectDevice').serialize(),
success: function(selectOptions){
$("#deviceAddress").empty();
for (var i = 0; i < selectOptions.length; i++){
$("#deviceAddress").append(
$("<option></option>")
.attr("value", selectOptions[i][0])
.text(selectOptions[i][1])
);
}
}
});
});
</script>
On the server side, use a route for the ajax post request.`As example this route changes the options depending on another form field (the information got send over with the data tag in the ajax request). In WTForms the select field options is a list of tuples containing an ID and name, I kept this the same on the python side.
#app.route('/selectform', methods=['POST'])
def updateselect():
deviceAmount = int(request.form.get('selectAmount'))
choices = [('device{}'.format(i), i) for i in range(deviceAmount)]
response = make_response(json.dumps(choices))
response.content_type = 'application/jsons'
return response`
Only one remark: the ajax request is performed on dropping down and on collapsing. The last part is not necessary of course, there is probably a way to structure the jquery so it only requests on dropdown.

How bind select options in the HTML with two pre-defined values to insert data in mongodb

I create an event creator in my admin dashboard, and everything is working ok, but now i need insert a new field:
info: Object
In my HTML event creator, i have this selection:
<label for="info">Information Type:</label>
<select id="info" name="info">
<option>Normal</option>
<option>Special</option>
</select>
With a post to /create
When this event arrive in my controller, i need save all the form inputs in my database, and is fine, this part is 100% working.
But, before make the save, i am using this code to bind the select option with the real value of the field info in the database:
event.pre('save', function(next) {
if (this.info === 'Normal') {
this.info = ['this text', 'is one text, but i want show as a list', 'that's why i am doing this']
} else if (this.info === 'Special') {
this.info = ['same', 'happens', 'here']
}
});
I want know if this is right, is working, but for me looks wrong.
So for example, if i choose 'Normal', will appear like this:
<ul>
<li>This text</li>
<li>is one text, but i want show as a list</li>
<li>that's why i am doing this</li>
</ul>
I want know if the whole thing is right, and if not, how to do it right. I also want alternatives using only HTML if possible, without using the pre save.
Thanks in advance.
If your info field's values are constant I think your solution is the best.
But if you need to use dynamic values for your info field you might change your codes as like here;
http://jsfiddle.net/oprz2p2e/
If you have a lot of fields on your form, you can collect your data using jQuery $("#yourFormId").serialize() method.
ps: I think you know how to show this data using EJS. You can list info field values using forEach together EJS.

How to make all the fields visible in the new Task form of Tasks List in SharePoint?

I have created a Tasks List in SharePoint. When I try to add a new Task, it opens a form with few visible fields like TaskName, StartDate, DueDate, Description, AssignedTo. When I click on 'ShowMore', then it is showing all the remaining fields like %complete, TaskStatus, Priority, Comments, ExpectedDueDate.
Issue: I want all the fields to be visible from the start without clicking on 'ShowMore', because some people might get confused with this option and may skip filling these fields. Can someone please kindly suggest how to achieve this. Any help is greatly appreciated. Thank you!
Unfortunately there is no such setting that allows to configure fields visibility in tasks form AFIK.
But task form could be customized in order to display all the fields as demonstrated below.
Since it is a SharePoint 2013 environment, the following approach is suggested:
Create rendering template to display all the fields in New & Edit forms
Update Task web part in New & Edit forms pages
Template file
The following example demonstrates how to display all the fields of Task form:
(function () {
function preTaskFormRenderer(renderCtx) {
rlfiShowMore();
}
function registerRenderer()
{
var ctxForm = {};
ctxForm.Templates = {};
ctxForm.OnPreRender = preTaskFormRenderer;
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(ctxForm);
}
ExecuteOrDelayUntilScriptLoaded(registerRenderer, 'clienttemplates.js');
})();
How to apply changes
Upload the specified script (lets name it TaskForm.js) into SharePoint Site Assets library
Open New Form page in edit mode and go to Tasks web part properties
Specify JS Link property located under Miscellaneous group: ~sitecollection/SiteAssets/TaskForm.js (see pic. 1)
Save changes and repeat steps 2-4 for Edit form
I prefer other methods to the JavaScript workaround to really solve the problem:
1. You can change the list form assigned to the local Task content type, for example via PowerShell:
$web = Get-SPWeb http://YourSharePointSite
$list = $web.Lists["Tasks"]
$ct = $list.ContentTypes[0]
$ct.DisplayFormTemplateName = "ListForm"
$ct.NewFormTemplateName = "ListForm"
$ct.EditFormTemplateName = "ListForm"
$ct.Update()
You can set the list form assigned to the ListFormWebPart via SharePoint Designer
Create your own control template and add the ShowExpanded="true" attribute to the TaskListFieldIterator control
Pass the Expanded=1 in the request query string like NewForm.aspx?Expanded=1
Change the default column order of the local Task content type
All of these have the effect of displaying all the fields without the "Show More" button. You can read more about these methods here:
http://pholpar.wordpress.com/2014/11/01/no-more-show-more-in-tasks-lists/

Categories