0
votes

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?

1
u need to share what you are doing in the view, share the view code? what are the scenarios of success and fail?Exprator
the view code isnt important. I hard coded itSamuel
But if you want to know its: class MainView(View): def get(self, request): return ... (above)Samuel
yeah so it will never fail as u r not doing anything, as ajax is getting the view by the URL mentioned, so it's a success. so if u want error just change the order of the success and error response returnExprator
no, that isnt the problem i change it up for testingSamuel

1 Answers

1
votes

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);
        }
    })
})