GET with AJAX Fetch

GET with AJAX Fetch

AJAX allows the browser to communicate with the server without reloading the page.
In this example, a GET request is sent using the Fetch API, and Django returns a JSON response.

 

Django Views

from django.views import View
from django.views.generic import TemplateView
from django.http import JsonResponse

class index(TemplateView):
    template_name = 'polls/index.html'


class get_param(View):
    def get(self, request, *args, **kwargs):
        param = request.GET.get('param')

        print(param)

        context = {}
        context['param'] = param
        context['message'] = 'Reply with some text!'

        return JsonResponse(context)

 

URL configuration

urlpatterns = [
    path("", index.as_view(), name="index"),
	path("get_param/", get_param.as_view(), name="get_param"),
]

 

Template example

<a href="{% url 'get_param' %}?param=value1" onclick="loadData(event)">Value 1</a> <br>
<a href="{% url 'get_param' %}?param=value2" onclick="loadData(event)">Value 2</a>

<script>
    function loadData(event) {
        event.preventDefault();  

        const href = event.currentTarget.getAttribute('href');

        fetch(href)
            .then(response => response.json())
            .then(data => console.log(data))  
            .catch(error => console.error('Error:', error));  
    }
</script>

Tested with Django 4.2