1

I have ajax function like this which is working fine:

 function show_tasks() {
              $.ajax({
                        type: "GET",
                        url: "/2/todos/", //I want url: "/{{ category.id }}/todos/"
                        success: function(data){
                             $('#tasks').html(data)
                             .css("display", "block");       
                        }
                    });
        }

HTML contents

{% for category in categories %}
    <tr>
    <td width="5%"><input type="checkbox" value="{{ category.id }}" name="category_name" id="category{{ forloop.counter }}" /></td>   
    <td>
        <a data-toggle="tooltip" title="Show Tasks" onclick="show_tasks()">
            {{ category.name }}</a>

{% endfor %}

How can I do this?

2 Answers 2

3

Construct url in html with template processor, something like:

...
<a data-toggle="tooltip" title="Show Tasks" 
   onclick="show_tasks({% url 'category_todo' category.id %})">
...

and add url support in your javascript:

function show_tasks(url){...
   url: url,
   ...
}
Sign up to request clarification or add additional context in comments.

4 Comments

I passed {{category_id}} as argument to show_tasks() function and it worked. Thanks mate!
-1, This is real bad practice. If you're doing this you should be damn sure about what you're doing.
@limelights yes, you can construct url in js, but what if your url patter changes later on? say it will be /cat.id/todos/new/ or so? It is surely easier to maintain it all in one place, in urls.py. And will appreciate few words on why this is bad practice, can't in fact imagine any except html size.
1 - You're coupling your view with your javascript by using onclick - this leads to several things but most your forgoing the unobtrusive javascript design process. 2 - You're currently mixing 3 languages in one go. html(javascript(django-template-lang)). If you want to have the url still "maintainable", put the URL in a hidden input tag and fetch it via javascript instead.
2

You can use this to get the dom element that generated the click event in your show_tasks function. From there, just use jquery to find the value of the adjacent checkbox.

You can do something like var category = $(this).closest('input').attr('value') in show_tasks to get the category id and supply it to $.ajax like url : "/" + category + "/todos/".

Comments

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.