A
A
Artem Rassadin2021-08-09 20:55:06
AJAX
Artem Rassadin, 2021-08-09 20:55:06

How to pass a parameter from ajax to django and process it?

Good evening! I need to pass a number from js and process it in django and then return it back. I can't pass a number and process it.

JavaScript

publicImg.forEach(icon => {
  icon.addEventListener('click', () => {
    $.ajax({
      type: "GET",
      url: "http://127.0.0.1:8000/photo/click_on_photo/",
      data: icon.dataset.counter,
      dataType: "text",
      cache: false,
      success: function(data) {
        loadComments(data)
      }
    })
  })
})

views.py
def clicked_photo(request):

    a = 1 # эта переменная будет передаваться в ajax запросе

    if request.method == "GET":
        icon = Image.objects.get(id = a)
        comms = ImageComment.objects.filter(comment_id = icon.id)

        object_info = { 
            "image": icon.icon.url, 
            "comms": computeComs(comms)
        }
            
    return JsonResponse(object_info)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artem Rassadin, 2021-08-09
@Artyom02

In general, after a long search on the Internet, I found a solution. It was necessary to replace the key in the function of creating an ajax request, change type to method . For those who will have a similar problem:
1. you will need to pass the object in the function of creating an ajax request in the data field
2. In order to accept this value, you will need to write elem = request.GET.get after request.method == "GET" ('<object key from ajax request>')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question