0

How do you when making an ajax request to a view return the template data to the jquery call.

As an example, i am making an ajax call this way.

<script>
  function getProfile(username) {
     $.getJSON("/profiles/"+username, { username:{{ username }}}, function(json){
                            alert("Was successful?: " + json['success']);
                        });
                    }
   function addClickHandlers() {
           $(".person-name").click( function()
                getProfile(result.user.username) });
                    }
                    $(document).ready(addClickHandlers);
  </script>

My django view

def profiles_view(request, username):
#    if username:
#        selected_user = User.objects.get(username = username)
    results = {'success':False}
    if request.method == u'GET':
        GET = request.GET
        if GET.has_key(u'username'):
            results = {'success':True}
    json = simplejson.dumps(results)

    return HttpResponse(json, mimetype='application/json')

Can i pass my template view profiles_view.html to the HttpResponse? i am not sure where my template comes in?

Hui Zheng
  • 10,084
  • 2
  • 35
  • 40
Warz
  • 7,386
  • 14
  • 68
  • 120
  • 1
    You can take a look at this question, if you find it useful [link](http://stackoverflow.com/questions/11104690/django-how-to-return-model-formset-in-ajax-and-use-in-template) – akotian Feb 06 '13 at 02:57

2 Answers2

0

If you need both HTML view and JSON view, you may need two responses. First is from TemplateResponse, second one is from HttpResponse. Two requests seem inefficient, but the first request is once for all, afterwards you only need JSON response by use of AJAX request.

You can return a template by:

 return TemplateResponse(request, "profiles_view.html", results)
Hui Zheng
  • 10,084
  • 2
  • 35
  • 40
  • I only need a TemplateResponse, the only reason i am making an ajax request is to display html in specific div. any examples on TemplateResponse? – Warz Feb 06 '13 at 02:47
  • I added a snippet in my answer. If you only need one ajax request, you can consider merging two requests in one template view, otherwise you'd better separate them. – Hui Zheng Feb 06 '13 at 02:53
0

You don't need a template if you are just going to pass data through ajax.

danniemorales
  • 43
  • 1
  • 4
  • i want to load the template in a specific div and i am making the ajax request in the same page. – Warz Feb 06 '13 at 02:55