Home > Net >  How to get passed JSON Data on Ajax Error?
How to get passed JSON Data on Ajax Error?

Time:09-22

I am using Django and Ajax. Im my view I have:

class MainView(View):
    def get(self, request):
        if not request.is_ajax():
            return render(request, "main.html")
        
        # hard coded both options for testing
        return JsonResponse({"data": "xyz"}, status=400) 
        # return JsonResponse({"data": "xyz"}, status=200) 

my ajax function looks like:

$("#start_calculation_button").click(function () {
    $.ajax({
        url: "/",
        type: 'get',
        data: {
            ...
        },
        success: function (response) {
            console.log(response.data);
        },
        error: function (response) {
            console.log(response.data);
        }
    })
})

But only the success function works? While the error part just gives back undefined

Any idea's why it is that way? How can I fix it?

CodePudding user response:

The parameters of success and error are different, in case of a success, these parameters are result, status, and xhr whereas for error, the parameters are xhr, status, and error. You thus should parse the xhr data with:

$("#start_calculation_button").click(function () {
    $.ajax({
        // ⋮
        success: function (response) {
            console.log(response.data);
        },
        error: function(xhr) {
            var err = JSON.parse(xhr.responseText);
            console.log(err.data);
        }
    })
})
  • Related