Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Ajax call to update a Django view

Tags:

ajax

django

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.

like image 854
mcw Avatar asked Jan 07 '14 21:01

mcw


People also ask

Can you use AJAX with Django?

when you need to initial a page with data at first, you can use Django with Ajax. But in some case, you just need a static page without anything from server, you need not use Django template. If you don't think Ajax is the best practice.

How send data from AJAX to Django?

To send and receive data to and from a web server, AJAX uses the following steps: Create an XMLHttpRequest object. Use the XMLHttpRequest object to exchange data asynchronously between the client and the server. Use JavaScript and the DOM to process the data.

Does AJAX improve performance?

Ajax's primary advantage is its ability to improve performance and usability for web applications. Ajax allows applications to render with no data. This reduces server traffic. Web developers can reduce the time taken to respond on both sides of the request.

How does AJAX save data in Django?

Create the AJAX View First, we set up an if statement to check if the request is a POST request. If it is a POST request, we pass the posted data stored in request. POST to the form—this is known as binding a form to a dataset. Next, we check the form to see if the submitted data is valid.


1 Answers

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.

like image 100
Brandon Avatar answered Sep 30 '22 14:09

Brandon