How to access fetched data in Ajax response using Django?

85 Views Asked by At

i am trying to access data from view function to ajax response.here i am Getting data in my Views.py and i want to access that data in ajax Response. i don't know hoe to do that?
Hare is my Code

in My Views.py

This is My views.py. i am calling this function via ajax.

def myfunction(request):
    if request.method=='POST':
        id=request.POST['id']
        result=MyModel.objects.filter(id=id) # in result variable i am getting all data like fname,,lname etc

here is my AJAX Call

    $.ajax({
            url: '/myfunction',
            method: 'POST',
            data: {
                'id' : id,
                 csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
            },
            success:function(result)
            {
                alert(result); // here i want to access values
            }
        });
  • in My view.py function , I am getting all data in variable 'result'. i Want to access the all values like fname,lname in my ajax response. 'result' variable is contain a multiple records.i will be thankfull if anyone can help me with this issue.
1

There are 1 best solutions below

0
On BEST ANSWER

Your views.py:

from django.http import JsonResponse
def myfunction(request):
    if request.method=='POST':
        id=request.POST['id']
        result=list(MyModel.objects.filter(id=id).values())
        return JsonResponse(result, safe=False)

In your ajax:

    $.ajax({
            url: '/myfunction',
            method: 'POST',
            data: {
                'id' : id,
                 csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
            },
            success:function(result)
            {
                console.log(result); <--- Here
            }
    });

Here--> Depending upon your response values you will be able to access. Firstly, you have to see how your server is sending data

Refs: JsonResponse | values