Skip to content

Django with ajax

In the ever-evolving landscape of web development, enhancing user experience is paramount. One powerful tool for achieving this is AJAX (Asynchronous JavaScript and XML), which allows for seamless, asynchronous communication between the client and server. When integrated with Django, a high-level Python web framework, AJAX can elevate your web applications to new heights of interactivity and responsiveness.

We need AJAX for dynamic, seamless, and responsive web experiences by enabling asynchronous communication between the client and server, reducing page reloads, enhancing user interaction, and improving performance.

Success

<div class="col-md-4">
    <div class="accordion" id="accordionExample3">
      <div class="accordion-item">
          <h2 class="accordion-header">
              <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseThree" aria-expanded="true" aria-controls="collapseOne">
                IT Services
              </button>
          </h2>
          {% for item in header_business %}
            {% if item.category == '3' %}
            <div id="collapseThree" class="accordion-collapse collapse show" data-bs-parent="#accordionExample3">
                <div class="accordion-body">
                  <a href="#" class="business-item-link" data-slug="{{ item.slug }}">{{ item.title }}</a>
                </div>
            </div>
            {% endif %}
          {% endfor %}
      </div>
    </div>
  </div>
  <div class="col-md-8">
    {% if not request.is_ajax %}
        <h5 class="bt__bussiness--title bt-sec-title">{{ business_item.title }}</h5>
        <div class="business-item-content">{{ business_item.content | safe }}</div>
    {% else %}
      <h5 class="bt__bussiness--title bt-sec-title"></h5>
      <div class="business-item-content"> </div>
    {% endif %}
  </div>
script
<script>
$(document).ready(function(){
    // Get CSRF token from cookie
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = cookies[i].trim();
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    var csrftoken = getCookie('csrftoken');

    // Handle click event for anchor tag with class 'business-item-link'
    $('.business-item-link').click(function(event) {
        // Prevent default behavior of anchor tag
        event.preventDefault();

        // Get the slug value from data attribute
        var slug = $(this).data('slug');

        // AJAX GET request to fetch data
        $.ajax({
            url: '/business/' + slug + '/ajax/',
            type: 'GET',
            beforeSend: function(xhr, settings) {
                // Include CSRF token in headers
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            },
            success: function(response){
                console.log('Response data:', response.title);

                // Ensure that response contains the title property
                if (response.hasOwnProperty('title')) {
                    // Update HTML content with received data
                    $('.bt__bussiness--title').text(response.title);
                }

                // Ensure that response contains the content property
                if (response.hasOwnProperty('content')) {
                    $('.business-item-content').html(response.content);
                }
            },
            error: function(xhr, errmsg, err){
                console.error('Error fetching data:', errmsg);
            }
        });
    });
});
</script>
from django.http import JsonResponse

...

class BusinessItemView(HeaderFooterMixin, TemplateView):
    template_name = 'business/business-item.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        slug = kwargs['slug']
        business_item = get_object_or_404(BusinessItem, slug=slug)
        context['business_item'] = business_item

        business_inner = BusinessInner.objects.first()
        context['business_inner'] = business_inner

        return context

    def get_ajax_data(self, request, *args, **kwargs):
        slug = kwargs['slug']
        business_item = get_object_or_404(BusinessItem, slug=slug)

        print("REQUEST xxxx")

        # Construct data to send in JSON response
        print("business_item: ", business_item)

        data = {
            'title': business_item.title,
            'content': business_item.content,
            # Add more data as needed
        }
        return JsonResponse(data)

    def dispatch(self, request, *args, **kwargs):
        # Check if it's an AJAX request
        # if request.is_ajax(): is depreciated
        if request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest':
            # If yes, call the get_ajax_data method
            return self.get_ajax_data(request, *args, **kwargs)
        else:
            # If not, call the parent dispatch method to handle the regular view
            return super().dispatch(request, *args, **kwargs)
urlpatterns = [
    path('', BusinessPageView.as_view(), name='inner'),
    path('<slug>/', BusinessItemView.as_view(), name='item'),
    path('<slug>/ajax/', BusinessItemView.as_view(), name='item_ajax'), 
]
base.html
<head>
    <script src="{% static 'js/jquery-3.7.1.min.js' %}"></script>
</head>
<body>

use script before body

Reference