I am trying to figure out how to write an AJAX function, and haven’t been able to find a tutorial that’s not over my head.
My HTML is:
<a href="{% url pay_provider id=statement.statement_id %}" id="pay_provider">Pay</a>
When a user clicks “Pay”, the following django would be executed via AJAX:
def pay_provider(request, statement_id):
FinancialStatements.objects.get(statement_id=statement_id).update(paid=1)
return redirect(...)
What would be the necessary url.py, views.py, and js in order to do this at the most basic level?
Well, you’ve got a couple of issues:
aelement to fire an ajax event. This isn’t a horrible idea, but it has overhead you may want to avoid.Finally, am I reading your
hrefcorrectly in that you are setting it to the script that returns the ajax response? Or are you trying to get it so that when they click on the link, it takes them to a new page while simultaneously sending an ajax request?If it’s the latter, I’d avoid it. If it’s the URL of the ajax responder, try this:
HTML/Python:
JQuery:
By setting the
post_urlright after the event handler, it avoids issues with$(this)getting overwritten by thepost()function and allows you to store your ajax URL in the link. While this could be an issue for browsers that don’t play nice, it does offer the benefit of reusing the same ajax function for several such links, for example:Now you can do:
Which will work on all 3 “action” links, but fire their own action script.