Chris Meek
Chris Meek

Reputation: 1523

How to get changes realtime with jquery in Django

I have made a little app that you can add people to and lists them all on a page. I used REST to produce a JSON api and jquery to get the results. How do I use JQuery to update any changes to the page without the need of a refreshing?

all.html

<ul id="people"></ul>

main.js

$(function (){
    var $people = $('#people');

    $.ajax({
        type: 'GET',
        url: '/all/api',
        success: function(people) {
            $.each(people, function(i, person) {
                $people.append('<li>name: ' + person.first_name+', last: '+ person.last_name + '</li>');
            });
        }
    });
});

api.py

class PersonList(APIView):
    def get(self, request, format=None):
        people = Person.objects.all()
        serialized_people = PersonSerializer(people, many=True)
        return Response(serialized_people.data)

Upvotes: 1

Views: 1245

Answers (1)

greenafrican
greenafrican

Reputation: 2546

If you are not going to use websockets and are going to use asynchronous calls then you can check for updates by running the AJAX call every so often:

var ajax_call = function() {
  var $people = $('#people');

  $.ajax({
      type: 'GET',
      url: '/all/api',
      success: function(people) {
        $.each(people, function(i, person) {
          $people.append('<li>name: ' + person.first_name+', last: '+ person.last_name + '</li>');
        });
      }
    });
};

var interval = 5000; // 5 secs
setInterval(ajax_call, interval);

You may want to include a 'has_changed' flag or return a 304 (Not Modified) status in the httpresponse if nothing has changed so that you can handle non-updates gracefully. You need to be careful with calls like this as people can leave pages open for days.

Upvotes: 2

Related Questions