abautista
abautista

Reputation: 2780

How to pass a JSON to a an Ajax request in Django?

I am trying to pass a dictionary as a Json to an Ajax request with the following code:

Views.py

from rest_framework.response import Response

class ChartData8(APIView):
    def tickets_per_day_results(request):
        if request.method == "POST":
            template_name = 'personal_website/tickets_per_day_results.html'
            year = request.POST.get('select_year', None)
            week = request.POST.get('select_week', None)
            ....do stuff...
            data = {"label_number_days": label_number_days,
                    "days_of_data": count_of_days}
        return render(request,template_name,{Response(data)})

Response is the class I use to convert data to a json format but then I have to wrap it as a dictionary {} so I can avoid the error context must be a dict rather than Response.

template_1

$.ajax({
    method: "POST",
    url: endpoint,
    dataType: 'json',
    contentType: "application/json",
    headers: {"X-CSRFToken": $.cookie("csrftoken")},
    success: function(data){
        console.log(data)
        label_number_days = data.label_number_days
        days_of_data = data.days_of_data
        setChart()

    },
    error: function(jqXHR,error_data, errorThrown){
        console.log("error on data")
        console.log(error_data)
        console.log(JSON.stringify(jqXHR))
        console.log("AJAX error: " + error_data + ' : ' + errorThrown)
    }
})

Everything works OK until the browser throws me the error AJAX error: parsererror : SyntaxError: Unexpected token < in JSON at position 0. This error is due to the fact that I am led to believe the response body is actually HTML and not Json.

My main question is: How can I convert the result to a Json so it can be read smoothly by Ajax?

Upvotes: 1

Views: 261

Answers (1)

Arpit Solanki
Arpit Solanki

Reputation: 9921

Couple of mistakes you need to see. APIView class can not contain individual methods like you implemented. You either have to implement get or post. You can read more about it here

class ChartData8(APIView):
    def post(self, request):
        year = request.POST.get('select_year', None)
        week = request.POST.get('select_week', None)
         #   ....do stuff...
        data = {"label_number_days": label_number_days,
                    "days_of_data": count_of_days}

        return Response(data)

Upvotes: 1

Related Questions