Using Ajax call to update a Django view

ajax, django

Solution

If you intend to return a response via Ajax that JavaScript can then use to update your DOM, you need to return an `HttpResponse`, preferably in JSON format, which can be passed to a handler in your $.ajax call. Example:

import json

from django.contrib.auth.models import User
from django.http import HttpResponse
from django.shortcuts import render


def index(request):
    if request.is_ajax():
        username = request.GET.get('user', '')
        user = User.objects.get(username=username)

        # do whatever processing you need
        # user.some_property = whatever

        # send back whatever properties you have updated
        json_response = {'user': {'some_property': user.some_property}}

        return HttpResponse(json.dumps(json_response),
            content_type='application/json')

    return render(request, 'index.html', {'user': ''})

Then in your JavaScript, you can do:

$.get('/index/', {user: response.name, page: page}, function(json_response) {
        console.log(json_response.user.some_property);
});

With this approach, a normal GET request to your view returns a rendered HTML template. For an Ajax request, the view returns an HttpResponse in JSON format that gets passed to the callback in the jQuery $.get call.

Problem

I am new to Django, and am stuck attempting to get a variable sent from ajax to be used in the Django view. My view: ``` def index(request): if (request.is_ajax()): username = request.GET['user'] else: username = '' context = {'user':username} return render(request, 'index.html', context) ``` and the ajax: ``` $.ajax({ url: '/index/', type: 'GET', data: {user: response.name, page: page} }); ``` My issue is that `username` does not update in the view, based on the ajax call. I know the ajax call is working properly, because upon looking at the network response it is passing the proper updated username. What I believe is happening is that the view is loaded, then the ajax call occurs and updates username, but the view is not re-rendered and thus won't change. I have tried putting another render after getting the username, but that did not change anything, and I have also made a separate view for handling the ajax call, but that doesn't seem to work either, since the view always loads without ajax request being true. What is the way to get this working? Thanks for any help.

Original source