I encountered some strange issues with Ajax while developing an application in Django. My website has 4 forms that need to be processed using Ajax, and two of them are working perfectly fine. However, the other 2 forms seem to have no idea about Ajax. Let's take a look at the working and non-working forms.
views.py
Working Form View
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')
Non-Working Form View
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 for Working Form
<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 for Non-Working Form
<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>
main.js
Script for Working Form
$('#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;
});
Script for Non-Working Form
$('#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;
});
The first case functions perfectly, whereas in the second case, Ajax doesn't seem to initiate at all (it simply redirects me to the page with HttpResponse). What could be causing this issue?