Reputation: 163
Below are the details. I am able to get updated "questions_in_topic" variable in views when select option is changed i.e. ajax call is made. Ajax call is updating the "questions_in_topic" variable based on selected value in dropdown. But these changes are not reflected in template. i.e. on template, I still get old values.
urls.py
url(r'^interview/add/questions/library', recruiter_views.add_question_library, name='add_question_library'),
views.py
def add_question_library(request):
question_topics = QuestionTopic.objects.values('question_id__description', 'topic_id__name','question_id','topic_id').order_by('topic_id__name','question_id__description')
all_topics = Topic.objects.all()
questions_in_topic = QuestionTopic.objects.values('question_id__description').order_by('question_id__description')
if request.is_ajax():
if 'topicId' in request.POST:
print("xx")
questions_in_topic = QuestionTopic.objects.filter(topic_id=request.POST['topicId']).values('question_id__description').order_by('question_id__description')
else:
print("yy")
questions_in_topic = QuestionTopic.objects.values('question_id__description').order_by('question_id__description')
print(questions_in_topic)
context = { 'question_topics': question_topics, 'all_topics': all_topics,'questions_in_topic':questions_in_topic,}
return render(request, 'recruiter/add_question_library.html', context)
add_question_library.html
<select id="topic" name="topic_list" class="form-control topic_select">
{% for topic in all_topics %}
<option data-topic="{{topic.id}}" value="{{topic.name}}">{{topic.name}}</option>
{% endfor %}
</select>
<ul class="list-unstyled">
{% for x in questions_in_topic %}
<li class="list-unstyled">{{ x.question_id__description }}</li>
{% endfor %}
</ul>
ajax
var topicId = $(".topic_select option:selected").attr("data-topic");
$(".topic_select").change(function(){
var topicId = $(".topic_select option:selected").attr("data-topic");
$.ajax({
type: "POST",
url: "{% url 'recruiter:add_question_library' %}",
data: {
topicId: topicId,
'csrfmiddlewaretoken': '{{ csrf_token }}',
},
success: function(){
// alert("Showing questions from topic " + topicId);
}
});
});
Upvotes: 1
Views: 461
Reputation: 8525
With the request coming from view after the ajax call, you can do this:
// stuff
success: function(response){
// $("taget").replaceWith($("target",response));
$("ul.list-unstyled").replaceWith($("ul.list-unstyled",response));
}
You may have multiple ul.list-unstyled
in your project, I suggest that you add a unique ID to the list.
Upvotes: 2