На странице у меня есть выпадающий список (когда я меняю выбранную опцию, первый ajax срабатывает). Сначала ajax работает нормально, а страница обновляется. После обновления страницы у меня есть кнопка добавления в пользовательском интерфейсе, после нажатия которой запускается второй ajax. Надо отправить форму. Но кнопка добавления AJAX (второй AJAX) работает, только если я не запускаю первый AJAX. Второй ajax даже не вызывается, если я запускаю первый ajax до него.
Я подозреваю, что после вызова первого ajax элемент .add-question-form может быть недоступен в DOM
Первый Аякс:
var topicId = $(".topic_select option:selected").attr("data-topic");
$(".topic_select").change(function(){
var topicId = $(".topic_select option:selected").attr("data-topic");
if (topicId == undefined){ topicId = 999999; };
$.ajax({
type: "GET",
url: "{% url 'recruiter:add_question_library' %}",
data: {
topicId: topicId,
},
success: function(response){
// alert("Showing questions from topic " + topicId);
$("#question_list").replaceWith($("#question_list",response));
}
});
});
Второй Ajax:
$('.add-question-form').on('submit',function(e){
alert("hh");
e.preventDefault();
var $this = $(this);
var qstn_id = $this.attr('id').split('_')[1];
$.ajax({
type: "POST",
url: "{% url 'recruiter:add_question_to_interview' %}",
data: {
qstn_id: qstn_id,
'csrfmiddlewaretoken': '{{ csrf_token }}',
},
success: function(response){
// $("#question-alert").animate({right: '20%'}, "slow");
// $('#question-alert').append('<div class="alert alert-success alert-dismissible fade show" role="alert"><strong>Question added to interview</strong><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button></div>');
alert("Added Question with id " + qstn_id);
}
});
});
HTML
<div class="col-md-4">
<select id="topic" name="topic_list" class="form-control topic_select">
<option>All Topics</option>
{% for topic in all_topics %}
<option data-topic="{{topic.id}}" value="{{topic.name}}">{{topic.name}}</option>
{% endfor %}
</select>
</div>
<table class="table table-striped" id="question_list">
<tbody>
{% for x in questions_in_topic %}
<tr>
<td class="w-90">
{{ x.question_id__description }}
<span class="badge badge-pill badge-success">{{ x.topic_id__name }}</span>
</td>
<td class="w-10">
<form class="form-inline add-question-form" id="addqstnform_{{ x.question_id }}" >
{% csrf_token %}
<button type="submit" class="btn btn-add-question" data-questionid="{{ x.question_id }}"
style="background-color: #ff7a59;color: white; font-size:0.8em; padding: 0.15em 0.5em">+</button>
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table>