stephan
stephan

Reputation: 2393

How can I pass a dynamic URL in a POST request via jQuery?

I am trying to do this:

<script>
 $(document).ready(function() {
    $(".delete_button").click(function() {
        var id = $(this).attr('id');
        $.ajax({
            type: "POST",
            url: "/accounts/{{ request.user.username }}/profile_listview",
            data: { entryname:id },
            success: function(response){
                alert(response.success);
            }
        });
        return false;
    });
});
</script>

But I need to find a solution to pass in the dynamic URL since Django template variables won't work in this scenario. How can I accomplish this?

Upvotes: 1

Views: 4511

Answers (2)

sthzg
sthzg

Reputation: 5554

If the variable you need to pass is always the same (like request.user.username will be always the same for one user) you could render a javascript object containing all the options that you need to access to build your url.

<script type="text/javascript">
    var __MYAPP_CONFIG__ = {
      username: JSON.stringify({{ request.user.username }})
    };
</script>

Then, in your script you could bring that dynamic part in by accessing my_app.username.

$.ajax({
    # ...
    url: "/accounts/" + window.__MYAPP_CONFIG__.username + "/profile_listview",
    # ...
});

What I like about this approach is that it (in my opinion) provides a rather generic structure for projects that grow with time. For sites that are big enough I mostly end up having one configuration object with a structure like my_project.my_app1.options, my_project.my_app2.options, etc. That way all apps that might need it are namespaced and I have a central location where I know to find my options.

Upvotes: 3

suselrd
suselrd

Reputation: 794

Maybe you could use a html5's data attribute, something like:

<a class="delete_button" ... data-url="{% url 'my_url_name' username=request.user.username %}">Delete</a>

This way, is more DRY.

Then, in the script, you use that data as the url to post to:

$.ajax({ type: "POST", url: $(this).data('url'), data: { entryname:id }, success: function(response){ alert(response.success); } });

Upvotes: 3

Related Questions