Reputation: 1961
I'm calling sortMovie()
ajax function, whenever the user changes a drop down box. This is working, but I'm getting some strange output. The ajax response loads the same template twice. I think it is because of return render_to_response('movie/movie_list.html',{'movies':movies})
Can anyone help me? Here is screenshot of the issue. Thanks.
The dropdown code:
<select name="movielist" onchange="sortMovie(this.value)">
<option value="">Choose</option>
{% for category in categories %}
<option value="{{ category.id}}">{{category.name}}</option>
{% endfor %}
</select>
The code from the view:
def movie_sort(request):
try:
movies = Movie.objects.filter(language=request.GET.get('q'))
except:
movies = Movie.objects.all()
return render_to_response('movie/movie_list.html',{'movies':movies})
And the ajax:
function sortMovie(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML = "";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "/moviesort/?q=" + str, true);
xmlhttp.send();
}
Edit: Here is mybase. Here is my movie_details.htm. Last one is movie_list.html
Update : I found If I remove {% extends 'base.html' %}
from movie_list.html'. Then It worked. So It mean I have to create different
template` for this view.
Upvotes: 0
Views: 123
Reputation: 9474
Judging by the screenshot you posted and based on your comment, what seems to happen is that the entire page is inserted into the innerHTML
of the tag you are updating. The issue then is that either the ajax request reloads the entire page, or the HTML that is received from the ajax call contains more markup than you expect it to contain.
Based on the sources you posted, the latter seems the case: remove the {% extends 'base.html' %}
from movie_list.html
, and everything should be fine.
Upvotes: 1
Reputation: 599628
Well, yes. Your Ajax is posting to the same view as the original page, and the view is just returning a rendered template which your Javascript is faithfully inserting into the page.
Your view should be checking for an Ajax query and returning JSON, rather than a rendered template. Usually you would use request.is_ajax()
, but that flag will not be set as you are not using a JS library (which you really should be, these days). You might find it easier to use a separate view just for your Ajax request, and return JSON from there.
Upvotes: 0