0
 url(r'^(?P<code>[-\w]+)/$',views.Listing.as_view(),name='stat_details'),

How can I access this django url from my javascript file where I am sending an ajax call to this url:

/mycode/

$(document).ready(function(){
  var url = {% url stat_details code='abc' %}.replace('abc', 'mycode');
  alert(url);
  $.ajax({
      url: url,
      success:function(result){
        populateTable(result.data.m_data);
      },
      error:function(xhr){
        alert("Fail"+ xhr.status+ " "+ xhr.responseText);
      }
  });
});

This doesn't work.Can someone help me in correcting this.

Thanks

1 Answer 1

1

Firstly,to avoid any confusion,update your URL as :

url(r'^stat_details/(?P<code>[-\w]+)/$',views.Listing.as_view(),name='stat_details'),

And then render your url just as a string like this :

<script>
    $(document).ready(function(){
      var code = your_code;
      var url = "/stat_details/"+ code;
      alert(url);
      $.ajax({
          url: url,
          success:function(result){
            populateTable(result.data.m_data);
          },
          error:function(xhr){
            alert("Fail"+ xhr.status+ " "+ xhr.responseText);
          }
      });
    });

</script>

You don't need to complicate the URL request process and please don't forget the first / in var url = "/stat_details/"+ code; And if the method is post,then you should also mention it. Thanks.

Sign up to request clarification or add additional context in comments.

3 Comments

yeah this worked. can you also tell how can I access a django variable rendered to a html page in javascript?
@lola A Django template variable can be rendered as "{{your_variable}}" in Javascript code and Don't forget the " " double quotes.
but this doesn't work if the javascript is in another file.

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.