Как заставить несколько функций ajax работать правильно
У меня есть шаблон django с двумя формами в нем. Когда отправляется первая форма, срабатывает ajax-функция, и на странице отображается вторая форма. Когда отправляется вторая форма, функция ajax, связанная с этой формой, похоже, не работает.
В целях тестирования я попробовал отправить вторую форму перед отправкой первой, и функция ajax сработала, как и ожидалось. Как сделать так, чтобы несколько функций ajax работали корректно одна за другой?
Это мой шаблон
<div class="form_container">
<div class="form">
<form action="{% url 'process_url' %}" method="post" id="youtube_link_form">
{% csrf_token %}
<div class="input-group mb-3">
<input type="text" class="form-control youtube_link_input"
placeholder="Put the youtube link or video id" aria-label="youtube_submit_input"
aria-describedby="youtube_submit_button" name="youtube_submit_input">
<button class="btn youtube_submit_button" type="submit" id="youtube_submit_button">Submit</button>
</div>
</form>
</div>
</div>
<div class="user_target_select">
<div class="target_buttons d-flex justify-content-between">
<form method="get" action="{% url 'user_select_positive' %}" id="positive_user_select_form">
<input type="hidden" id="positive_user_select_input" name="positive_user_select_input">
<button class="target_button btn btn-outline-success" id="user_select_positive" type="submit"
data-bs-toggle="modal" data-bs-target="#thank_model">Positive</button>
</form>
</div>
</div>
Здесь div user_target_select по умолчанию скрыт. Когда первая форма отправлена, div отображается.
Это мой js файл
function youtube_link_form_submit(event) {
event.preventDefault();
var data = new FormData($('#youtube_link_form').get(0));
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: data,
cache: false,
processData: false,
contentType: false,
success: function (data) {
$('#status').append(data['status'])
$('.user_target_select').css('display', 'block');
if (data['status'] == 'video parsed successfully') {
console.log('data submitted successfully')
}
}
})
return false;
}
function positive_user_select_form_submit(event) {
event.preventDefault();
var data = $(this).serialize();
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: data,
cache: false,
processData: false,
contentType: false,
success: function (data) {
console.log(data)
$('.user_target_select').css('display', 'none');
}
})
return false;
}
// trigger the above functions on form submit
$(function () {
$('#youtube_link_form').submit(youtube_link_form_submit);
})
$(function () {
$('#positive_user_select_form').submit(positive_user_select_form_submit);
})
Currently when the second form is submitted the ajax function is not called. I know this because the event.preventDefault() is not working and the JsonResponse from the django view is executed on a new page. The URL also changes. If I try to submit the second form without submitting the first form, the function works as expected.