Feel like I am stumbling over something fairly simple here.
I am not understanding something about AJAX and Flask.
I have a project wherein I display mongodb records in the browser, which has been working fine.
I added functionality for users to increment votes on a record; to Vote it up if they like it. But originally I was then refreshing the entire page with the new vote, using a redirect, which is clumsy. So I am trying to get AJAX to send the data over to the mongodb record and then update the span where I want the votes to appear without having to reload the entire page.
Problem is, the setup I have going, while still updating the record, is now loading a new page with the HTML i want returned only to the span where the vote tally should be (that is, it's loading a new page with only the word "test" in it (the test value I am currently returning)).
The jQuery (the library I am using) is loading fine and there are no other problems (as far as I can tell).
I have the relevant HTML and JS here:
<!-- All Standard HTML up here, removed for simplicity -->
<script>
$('#vote_link').bind('click', function(e){
e.preventDefault();
var url = $(this).attr('href');
$('#vote_tally').load(url);
});
</script>
<a href='/vote_up/{{ item._id }}' id='vote_link'>Vote for Me!</a><br>
Likes: <span id='vote_tally'>{{ item.votes }}</span>
<!-- All Standard HTML down here, removed for simplicity -->
and the python is here:
from flask import Flask, render_template, request, redirect, flash, jsonify
#from mongokit import Connection, Document
#from flask.ext.pymongo import PyMongo
from pymongo import Connection#, json_util
#from pymongo.objectid import ObjectId #this is deprecated
import bson.objectid
'''my pymongo connection - removed for simplicity'''
'''bunch of other routes - also removed for same reason'''
#increment a vote
@app.route('/vote_up/<this_record>')
def vote_up(this_record):
vandalisms.update({'_id':bson.objectid.ObjectId(this_record)},
{"$inc" : { "votes": 1 }}, upsert=True)
'''
also trying to return value for votes field from mongo record, but one step at a
time here
'''
#result = vandalisms.find({'_id':bson.objectid.ObjectId(this_record)}, {'votes':1})
result = 'test'
return result
I am also having trouble figuring out how to return the individual vote value for the specified mongodb record back to the browser, even with jsonify (which returns {"votes":'_id'}, but that's another issue. Hopefully someone can help me understand how to make AJAX work for me with Flask in this regard.
Thanks in advance,
Edit-24Jul2012-2:27PM CST:
I suspect that the jQuery isn't even activating. It seems to be loading the new page based on the link's href attribute, hence it's no use to have e.prevenDefault();
when that's not being run. Furthermore, an alert('I have been clicked');
never runs when the click event takes place. Again, the jQuery is loaded, but the click event is not activating the jQuery, and I don't know why not.