Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DJANGO : Update div with AJAX

I am building a chat application. So far I am adding chat messages with jquery $.post() and this works fine.

Now I need to retrieve the latest chat message from the table and append the list on the chat page. I am new to Django, so please go slow.

So how do I get data from the chat table back to the chat page?

Thanks in advance!

like image 630
Harry Avatar asked Dec 10 '09 09:12

Harry


1 Answers

My favorite technique for this kind of thing is to use an inclusion tag

basically you make a separate template for rendering the individual objects in the page template

page template:

{% load message_tags %}    

<h3>Messages</h3>
<div class="message_list">
    {% for message in messages %}
        {% render_message message %}
    {% endfor %}
</div>

templatetags/message_tags.py:

from django import template

register = template.Library()

@register.inclusion_tag('individual_message.html')
def render_message(message):
    context_for_rendering_inclusion_tag = {'message': message}
    return context_for_rendering_inclusion_tag

now you can use the same template to render the the additional messages you want to add to the message_list div in a separate view which you can call from your ajax code

def ajax_retrieve_latest_message(request):
    # ... Get the lastest message
    render_to_response('individual_message.html', ... 

And your jQuery will look something like...

$.post(url_of_ajax_view, request_data, function(data, status) {
    if (status == 'success') {
        $(".message_list").append(data);
    }
});

For completeness, your individual_message.html file would contain all the markup for displaying the actual message on the page...

Hope this all helps :)

like image 147
Jiaaro Avatar answered Oct 11 '22 20:10

Jiaaro