Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialAleks Dahlberg
19,103 PointsCreating an Ajax function to handle vote system.
I am working on a basic voting system in Node and Express. My current system works but there are a bunch of flaws in it.
Firstly, each post created generates a new ajax script and the html is given a class which is the post id, that is also script is given the id of the post as its class selector. The way I have set this up means that eventually the feed will be filled with a large number of scripts all performing the same function - a post request to a url '/post._id/up (or down) when the up or down button is selected.
if posts
each post in posts
include ./includes/card.pug
<!--CARD-->
div(class="card ui")
div(class="content")
div(class="right floated meta")
a.button(href='/feed')
i(class="angle up icon" + post._id + 'up')
$('.#{post._id}down').click(function(){
$.post('/feed/#{post._id}/down')
})
;
$('.#{post._id}up').click(function(){
$.post('/feed/#{post._id}/up');
})
;
These scripts and pug html are generated each time a new post is made. I am using the pug tempting engine for the html. Referencing data from express uses the #{data} syntax.
Secondly I am new to express and ajax.
Is there a way to make this so I do not have to have the scripts created every time a new post is made?
1 Answer
Aleks Dahlberg
19,103 PointsI solved this by creating a seperate scripts file, importing it into the main pug layout and adding an id attribute to the pug html of: html pug file
i.angle.up.icon(id='up-' + post._id, onclick="upVote(this)")
and for the down
i.angle.up.icon(id='down-' + post._id, onclick="downVote(this)")
script file
function upVote(item) {
var id = item.getAttribute('id').split('-')[1];
console.log(id);
$.post('/feed/' + id + 'up');
}
function downVote(item) {
var id = item.getAttribute('id').split('-')[1];
console.log(id);
$.post('/feed/' + id + 'down');
}