1

I'm trying to pass a variable from my JQuery Ajax object via get method to my views.py file (in django)

I was using a class before and it was working just fine..

views.py working code:

class AjaxHandlerView(View):
    def get(self, request):
        text = request.GET.get('button_text')
        print()
        print(text)
        print()
        if request.is_ajax():
            return JsonResponse({'test': 'blah'})

        return render(request,'home.html' , {'name': 'Handled by AHV'}  ) 

app urls.py

from django.urls import path
from . import views
from .views import *

urlpatterns = [
    path('', AjaxHandlerView.as_view() ),
    path('ajaxg' , views.ajaxgtest, name="ajaxg" )
]

jquery ajax functions (ignore the post method)

  var test_str = "[0,0]";

    $(document).ready(function(){

      var csrf = $('input[name=csrfmiddlewaretoken]').val()

      $('#jq_btn').click(function(){
        $.ajax({
          url: '',
          type: 'get',
          data: {
            button_text: test_str
          },
          success: function(response) {
            $("#jq_btn").text(response.test + test_str);
            console.log(test_str);
          }
        });
      });

    $('#post_btn').click(function() {
      $.ajax({
          url: '',
          type: 'post',
          data: {
            text: test_str,
            csrfmiddlewaretoken: csrf

          },
          success: function(reponse) {
            test_str = reponse.postdata
            console.log(test_str);
          }

      })

    });

  });

However I wanted to use a specific function for specific methods.. so I tried using a def..

views.py that is not working:

def ajaxgtest(self, request):
    text = request.GET.get('button_text')
    print(text + "deffer")
    if request.is_ajax():
        return JsonResponse({'test': 'blah'})

    return render(request,'home.html' , {'name': 'Handled by AHV'}  )

As for the Jquery code, all I did was edit url: '' to url: 'ajaxg' (which is what I named the view in the urls.py file)

new jq ajax code:

      $('#jq_btn').click(function(){
        $.ajax({
          url: 'ajaxg',
          type: 'get',
          data: {
            button_text: test_str
          },
          success: function(response) {
            $("#jq_btn").text(response.test + test_str);
            console.log(test_str);
          }
        });
      });

I'm getting the error code;

TypeError: ajaxgtest() missing 1 required positional argument: 'request' [01/Jan/2021 01:25:31] "GET /ajaxg?button_text=%5B0%2C0%5D HTTP/1.1" 500 58077

I'm unsure where I need to put a request element, or what not..

jasonmzx
  • 507
  • 5
  • 15

0 Answers0