I would like to create an AJAX-based search for my webpage. So far I am able to send the form data and make the appropriate call to my Django model. What I am having a hard time with is just sending the Queryset back and having it rendered using the Django templating system. Your help/advice is greatly appreciated.
Here is the code I am working with.
views.py
if request.is_ajax():
if request.method == 'POST':
format = 'json'
mimetype = 'application/json'
try:
q = request.POST['obj']
o = Object.objects.filter(name__icontains=q)
return render_to_response( 'project_view_objects.html', {'username': request.user.username, 'results':o})
view.html
<script>
$(document).ready(function(){
$("#search_form").submit(function(event)
{
event.preventDefault();
$.ajax({
type: "POST",
url: "/objects/search/",
data: $(this).serialize(),
processData: false,
dataType: "json"
});
});});
</script>
<article>
<blockquote>
<form class="create_form" id="search_form">
<p>
<input id="objectSearchNameInput" type="text" name="obj" value="Object name">
<input type="submit" value="search objects">
</p>
</form>
</blockquote>
</article>
<br />
{% if results %}
<blockquote>
<aside class="column">
{% for object in results %}
<b><a href="#" class="extra-text-special">{{ object.name }}</a></b><br />
{% endfor %}
</aside>
<aside class="column">
{% for object in results %}
<font class="extra-text-nospecial">{{ object.created_when }}</font><br />
{% endfor %}
</aside>
</blockquote>
{% else %}
<p>haha</p>
{% endif %}
At the moment, all I see displayed on the page is ‘haha’.
The thing you’re missing is that the template has already been rendered by the time the AJAX is fired – as of course it must be, because templates are server-side and javascript is client-side.
So the thing to do is to get your Ajax views not to return JSON, but rendered templates, which your Javascript callback then inserts into the template.