Я разрабатываю приложение на django и столкнулся со странными проблемами с Ajax.На моем сайте 4 формы должны быть обработаны с использованием Ajax.И два из них работают отлично.Но 2 других вообще не слышали об Ajax.Рассмотрим рабочие и нерабочие формы.
views.py
просмотр рабочей формы
def login_user(request):
form = LoginForm(request.POST)
context = { 'form': form, }
if request.method == 'POST' and form.is_valid():
username = form.cleaned_data['user_login']
password = form.cleaned_data['user_password']
user = authenticate(username=username, password=password)
response_data = {}
if user and user.is_active:
login(request, user)
response_data['result'] = 'Ok'
else:
response_data['result'] = 'Bad'
return HttpResponse(json.dumps(response_data))
else:
return redirect('index')
просмотр нерабочей формы
def add_new_station(request, add_station_slug):
form = AddStationForm(request.POST)
myuser = get_object_or_404(User, id=request.user.id)
print(request.user)
if request.method == 'POST' and form.is_valid():
response_data = {}
UserStation.objects.create(
station=Station.objects.get(slug=add_station_slug),
impressions=form.cleaned_data['impressions'],
list=UserStationsList.objects.get(user=myuser)
response_data['result'] = 'Ok'
)
return HttpResponse(json.dumps(response_data))
else:
return redirect('index')
urls.py
urlpatterns = [
path('', index, name='index'),
path("add-in-list/<str:add_station_slug>/", add_new_station, name='new_station'),
path('login/', login_user, name='login_action'),
...
]
html
html рабочая форма
<form id="login_form" action="{% url 'login_action' %}" method="post">
{% csrf_token %}
{{ formlogin }}
<div class="text-center">
<button type="submit" class="btn btn-dark mt-2">Entry</button>
</div>
</form>
html нерабочая форма
<form id="add_station_form" action="{% url 'new_station' choice_station.slug %}" method="post">
{% csrf_token %}
{{ formaddstaion }}
<div class="text-center">
<button type="submit" class="btn btn-outline-success mt-2">I visited this station</button>
</div>
</form>
mian.js
рабочая форма скрипта
$('#login_form').submit(function() {
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function(response) {
data = JSON.parse(response)
if (data['result'] === "Ok"){
$('.login-message').hide()
location.reload()
}
else{
$('.login-message').show(100).html('wrong data')
}
}
});
return false;
});
скрипт не-рабочая форма
$('#add_station_form').submit(function() {
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function(response) {
data = JSON.parse(response)
alert('data') // try check, but ajax don't reach here
}
});
return false;
});
В первом случае все работает отлично, во втором Ajax вообще не запускается (я просто перенаправляю на страницу с помощью HttpResponce. Итак,в чем проблема?