lola lola - 25 days ago 9
Ajax Question

access django urls from javascript

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

Answer

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.