[Answered ]-Django with Ajax and jQuery

2👍

If you want to use ajax to refresh your page, you’ll need to do three things:

  • Add an entry to urls.py for the ajax call (or add a condition to your view function to process the request if it’s ajax)
  • Add the javascript block to make the ajax call and update the html/text with the new data
  • Add the code in your views.py to handle the ajax call and respond with json data

urls.py

url(r'/ajax-view-single/)/$', 'ajax_single_item', name='app_name_ajax_single_item'),

html/js

<script type="text/javascript" src="/js/json2.js"></script>
$("#view-single-item").click(function () {
        try {
            // get slug from html
            var slug = "";
            var data = {
                slug: slug
            };
            $.get('{% url app_name_ajax_single_item %}', data, function(data){

               // your data returned from django is in data
               alert(data.item_name);

            }, 'json');
            //$('#error').hide();
        }
        catch(err) {
            $('#error').html(err);
            $('#error').show();
        }
        return false;
    });

views.py

from django.http import HttpResponse
from django.utils import simplejson
from django.shortcuts import get_object_or_404

def ajax_single_item(request):
    '''gets single item'''
    if not request.is_ajax():
        return HttpResponse(simplejson.dumps({'result': False}))

    # get slug from data
    slug = request.GET.get('slug', None)

    # get item from slug
    item = get_object_or_404(Item, slug=slug)
    return HttpResponse(simplejson.dumps({
        'result': True,
        'item_name': item.name,
        'item_price': item.price,
        'item_desc': item.desc,
        'item_slug': item.slug
    }))

Leave a comment