stephan stephan - 1 year ago 60
Ajax Question

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

I am trying to do this:

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

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?

Answer Source

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 }})

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

    # ...
    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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download