How to work with Django ajax "GET method"

446 Views Asked by At

I want to do an ajax GET and POST method in Django. My post method is working well, but the GET method isn't. See my codes below.

Urls

path("getupdates/",views.getupdates,name="getupdates")

views

def getupdates(request):
 if request.user.is_authenticated:
  if request.method == "GET":
   user_instance = User.objects.filter(username=request.user.username)[0]
   info = userinfo.objects.filter(username=user_instance.username)
   game = spinwheel.objects.filter(user=info[0])
   get_value= request.body
   data = {"info":info}
   print(data)
   return render(request,'spin.html',{"info":info})

Js-ajax

$.ajax({
 url: 'getupdates/',
 // datatype: 'json',
 data : data,
 type: 'GET',
 sucess: function(data) {
  console.log("refreshed!")
 }
});

I wish to have the ajax GET method update some parts of my HTML.

1

There are 1 best solutions below

0
On

You can check request.is_ajax(). If this true the case you are returning JsonResponce with your data. And insert them into your html without reloading the entire page.

Example

class ViewName(View):
    def get(self, requst):
        if requst.is_ajax():
            # your code

            return JsonResponse({'data': data})

    def post(self, requst):
        # your code