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