Ajax "fail" function does not read reply Json

0

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})
    
asked by Eduardo 13.06.2017 в 18:27
source

1 answer

0

In the case of a fail , xhr does not receive data directly. Therefore you have to look for the JSON there with the errors.

.fail(function(xhr) {
   data = JSON.parse(xhr.responseText);
   $("#result").html(data.result);
   alert('error');
}
    
answered by 13.06.2017 / 19:05
source