peter
peter

Reputation: 1582

Django Ajax Button - When I move the JS logic for the button to a separate file, the button can't find my Django link

I've got a follow button working well when included in the tag in the HTML for the specific page I want to use it for:

function toggleFollow(){
      $.ajax({
        url: "{% url 'user_follow' view.kwargs.username %}",
        success: function(data) {
          $("#followCount").html(data.follower_count + ' Followers');
          $('#followElement').html(data.button);
          console.log(data);
        },
        error: function(error){
          console.log(error);
        }
      });
  };

But when I move this button to a separate file, I get the django error that "The current path didn't match any of these" and then it lists all of my paths. How do I call my django url inside of my button.js file?

Upvotes: 1

Views: 95

Answers (1)

catavaran
catavaran

Reputation: 45595

You can not use django template tags in the button.js file. You have to pass the url from the template to javascript function.

For example you can add the following code to your template file:

<script>
    window.USER_FOLLOW_URL = "{% url 'user_follow' view.kwargs.username %}";
</script>

And then use this variable in the button.js:

$.ajax({
    url: window.USER_FOLLOW_URL,
    ....
})

Upvotes: 1

Related Questions