jsanchezs jsanchezs - 6 months ago 26
Linux Question

Call django urls inside javascript on click event

I got a javascript onclick event inside a template, and i want to call one of my django urls with an id parameter from it, like this :

$(document).on('click', '.alink', function () {
var id = $(this).attr('id');
document.location.href ="{% url 'myapp:productdetail' id %}"
});


Course this is not working at all. Any idea ?

Thanks in advance !!

Answer

You are trying to access javascript variable that is created at user click on frontend within your Django template at the backend. But, you already know that it would not work.

A better option would be to reconstruct the url in javascript:

$(document).on('click', '.alink', function () {
    // Generate URL without "id" bit
    var url = "{% url 'myapp:productdetail' %}";

    var id = $(this).attr('id');

    // Construct the full URL with "id"
    document.location.href = url + "/" + id;
});

If you don't have a django url helper that would return a URL that you need, you can print out just any and simply replace it in javascript like so:

$(document).on('click', '.alink', function () {
    var url = "{% url 'myapp:productdetail' 123 %}";
    var id = $(this).attr('id');

    // Construct the full URL with "id"
    document.location.href = url.replace('123', id);
});
Comments