parikLS
parikLS

Reputation: 553

Proper way for direct access to page after AJAX call

I'm building web app using django as REST service, and jquery on front which retrieves data using AJAX requests, and then renders this data using custom functions. The main goal - application should not refresh the page, only ajax calls. For now, django renders only the one static page, and the other urls responds with JSON data.

urls example:

urlpatterns = [
    url(r'^api/item/(?P<pk>\d+)/$', ItemView.as_view(), name='item'),
    url(r'^', IndexView.as_view(), name='index'),
]

views:

class IndexView(View):
    def get(self, request, pk):
        return render(request, 'index.html')   

class ItemView(View, ErrorMixin):
    def get(self, request, pk):
        try:
            item = Item.objects.get(pk=pk)
            return HttpResponse(json.dumps({'status': 'success', 'message': '', 'data': item.serialize()}))
        except Item.DoesNotExist:
            return HttpResponse(json.dumps({'status': 'error', 'message': 'invalid item id'}))

On frontend, i'm using html history API to set urls after ajax calls. For example, for ajax call on http://example.com/api/item/1, i will set browser url to http://example.com/item/1.

I expect, that users may share such links for direct access to needed items, and i don't know proper way, how to process such requests, and render needed data.

I think there are 2 ways: First is to parse url on frontend, and make ajax call, depends on what url is it. For example, if url is http://example.com/item/1, i should make ajax call on http://example.com/api/item/1, and render returned data.

Second is to have separate logic for get request in django view:

def ItemView(View):
    def get(self, request):
        if request.is_ajax():
            return HttpResponse(json.dumps({'status': 'success', 'message': '', 'data': item.serialize()}))
        else:
            return render(request, 'templates/item.html', {'data': item'})

I am a little bit confused. In my opinion, second approach is not correlate with REST API, because i shouldn't render pages with data on back-end, only respond with JSON. Also i will have to create more templates.

And in the first approach, i will have to write huge if-else logic on front-end, because after url parse, i need to call proper rendering function, depends on what api call was that. Please advise the best approach

Upvotes: 0

Views: 331

Answers (1)

Nhor
Nhor

Reputation: 3940

If you want to change url without reloading the page forget about server side, it's just the matter of how will your frontend respond to specific API calls. When you're changing url in your browser (precisely window.location) you're basically telling it that new content is coming in, which is being executed as fetching new page content (with Django render() function) and reloading.

If I understand you correctly you just want to fetch JSON data (like you're doing with HttpResponse()) and then show it on the page without reloading. With jQuery you would do it by sending a request and then displaying its response content in a specific way, for example to change an element content on your page:

$.ajax({
    url: your_url
}).done(function(data) {
  $.('#yourelementid').val(data.message);
});

Upvotes: 0

Related Questions