Depending on whether the form is valid or not, " success " or " some errors " should appear in a div with id="results" .
The problem arises when the form is not valid.
In the " fail " Ajax function, only the " alert " is executed and the answer Json sent from Django is not read.
In the " done " function everything works correctly.
I'm using " Firebug " to see if the information is correctly sent and apparently there are no problems.
I leave the used codes. Thanks in advance.
Ajax.js
$(document).ready(function() {
$('#form').submit( function(event) {
event.preventDefault();
$.ajax({
data: $(this).serialize(),
type : 'POST',
dataType: 'json',
url:'/wind/buildings',
})
.done(function(data) {
$("#result").html(data.result);
$('html,body').animate({
scrollTop: $("#result").offset().top},
'slow');
alert('success');
})
.fail(function(data) {
$("#result").html(data.result);
alert('error');
});
});
})
Django View
def buildings(request):
if request.POST and request.is_ajax():
s_form = BuildingForm(request.POST)
if s_form.is_valid():
return JsonResponse({'result': 'success'})
else:
return JsonResponse({'result': 'some errors'}, status=400)
else:
s_form = BuildingForm()
return render(request, 'wind/buildings.html', {'s_form': s_form})