I was following cookbook and having a problem for the ajax part. I can 
click plus or minus to change the value for the first time, but it doesn't 
update the value next time it's clicked. Also, I don't get any flash 
message like 'you voted already' or 'vote recorded'.

What am I missing ?


Controller
-----------------------------------------------
def news_comments():
    news = db.news(request.args(0)) or redirect(URL('categories'))
    if auth.user:
        db.comment.news.default = news.id
        db.comment.posted_on.default = request.now
        db.comment.posted_by.default = auth.user.id
        form = crud.create(db.comment)
    comments = 
db(db.comment.news==news.id).select(orderby=db.comment.posted_on)
    return locals()

@auth.requires_login()
def vote():
    if not request.env.request_method=='POST': raise HTTP(400)
    news_id, mode = request.args(0), request.args(1)
    news = db.news(id=news_id)
    vote = db.vote(posted_by=auth.user.id, news=news_id)
    votes = news.votes
    value = (mode=='plus') and +1 or -1
    if vote and value*vote.value==1:
        message = 'you voted already'
    else:
        if vote:
            votes += value - vote.value
            vote.update_record(value=value)
        else:
            votes += value
            db.vote.insert(value=value, posted_by=auth.user.id, 
posted_on=request.now, news=news.id)
            news.update_record(votes=votes)
            message ='vote recorded'
        return "jQuery('#votes').html('%s');jQuery('.flash').\
                html('%s').slideDown();" % (votes, message)

View - news_comment.html
---------------------------------
{{extend 'layout.html'}}
<h5>{{=A(news.title, _href=news.link)}}</h5>
{{if auth.user:}}
<span id="votes">{{=news.votes}}</span>
<button id="plus" onclick="ajax('{{=URL('vote', args=(news.id, 'plus'))}}', 
[], ':eval')">plus</button>
<button id="minus" onclick="ajax('{{=URL('vote', args=(news.id, 
'minus'))}}', [], ':eval')">minus</button>
{{=form}}
{{pass}}
<table>
{{for comment in comments:}}
<tr>
    <td>{{=comment.posted_on}}</td>
    <td>{{=comment.posted_by.first_name}}: </td>
    <td>{{=MARKMIN(comment.body)}}</td>
</tr>
{{pass}}
</table>

Reply via email to