Reputation: 549
I am trying to create a simple web link toggle for following or unfollowing a question in my app. I got close using the info My Own Like Button: Django + Ajax -- How? but am not quite there.
My problem is that I cannot dynamically pass question.id to my JS function as the answer in the above link implies. Ie
The hard-wired JS code below DOES work. It passes '12'
as a valid param for the view tied to /question/follow-unfollow-inline/
. But when I try to replace '12'
with a context variable '{{ question.id }}'
from the template that calls this JS code, my function passes the string '{{ question.id }}'
back to /question/follow-unfollow-inline/
rather than it's value. How do I fix this?
$(function () {
$("#follow_unfollow_toggle").click(function () {
$.ajax({
type: "POST",
url: "/question/follow-unfollow-inline/",
data: { 'qid': '12' },
success: function (e) {
alert('Success!');
}
});
});
});
For now, I'm using @csrf_exempt
on my view, but I know I should pass it as data.
Upvotes: 2
Views: 1634
Reputation: 32532
You could define it on your anchor tag with data-
attribute:
Template:
<a id="follow_unfollow_toggle" href="#" data-qid="{{ question.id }}">Like</a>
Js file:
$(function () {
$("#follow_unfollow_toggle").click(function () {
$.ajax({
type: "POST",
url: "/question/follow-unfollow-inline/",
data: { 'qid': $(this).data('qid') },
success: function (e) {
alert('Success!');
}
});
});
});
Upvotes: 2