2

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.

5
  • Did you try having Django serve the JavaScript? Commented Feb 11, 2014 at 23:01
  • Hi. Not sure if this answers your question but when in Debug mode, all my static files are served by Django. Otherwise Amazon S3. Commented Feb 11, 2014 at 23:57
  • Stop serving it as a static file. Commented Feb 12, 2014 at 0:09
  • So insert the js directly into my template vs. calling from an external js file? Commented Feb 12, 2014 at 1:36
  • I tried that. It works if you only have one question to follow/unfollow, but I have a list of them. If I place my JS inside my loop, it works for the first question in the list only. If I place the JS outside the loop, I lose the content of the current question id. Commented Feb 12, 2014 at 2:12

1 Answer 1

2

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!');
            }
        });
    });
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @dolan that worked great. I also realized I needed to change id="follow_unfollow_toggle" to class="follow_unfollow_toggle" so that my JS function fires for any question in my list of questions, not just the first.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.