Yogi Yogi - 2 months ago 6
Ajax Question

How to fetch json response from another url in django?

I have created 2 views in django namely

def next_qn_url(request):
test_result1 = 'questionansewrchoice'
return JsonResponse({'test_result':test_result1})
def last_qn_url(request):
test_result2 = 'questionansewrchoice'
return JsonResponse({'test_result':test_result2})
def test(request):
test = 'testchoice'
return render(request, 'ap/test.html', {})


i have also registered these views in urls.py

urlpatterns = [
url(r'^test/$', views.test, name='test'),
url(r'^next_qn_url/$', views.test, name='next_qn_url'),
url(r'^last_qn_url/$', views.test, name='last_qn_url'),
url(r'.*', views.home, name='home'),
]


I send data from my test page to the other 2 views and try to fetch their json response and update my test page with the help of jquery getJSON function.

$.getJSON('/next_qn_url/', selected_qn_ans, function(data) {

console.log(data);

});

$.getJSON('/last_qn_url/', selected_qn_ans, function(data) {

console.log(data);

});


I am just giving a rough draft here. But in the jsonresponse, i get the whole test page again and again with all html but not json. Is it not correct way to do it or guide me through this process. Thanks

Answer

I'm not sure your urls are correct. The first 3 point to the same views.test Django view, which could explain why you get the test html continuously. In my understanding, calling the name of the url in the getJSON function is not the same as calling a view that happen to have a 'similar name'. The first argument in getJSON is an url name, not a view name.

I would try the following modification, see the difference in the second & third urls :

urlpatterns = [
    url(r'^test/$', views.test, name='test'),
    url(r'^next_qn_url/$', views.next_qn_url, name='next_qn_url'),
    url(r'^last_qn_url/$', views.last_qn_url, name='last_qn_url'),
    url(r'.*', views.home, name='home'),    
]

Hope it works.

Comments