Problem with ajax in Django

Hello dear experts. I ask for your help and tips.
js script:

save_walls.addEventListener("click", function () {
$.ajax({
url: '/save_events_json/',
            type: 'GET',
            contentType: 'application/json; charset=utf-8',        
            success: function(result) {
                alert(result);
            },
            error: function() {
                alert('Error!');
            }
        });
});

views.py:

def save_events_json(request):
    if request.is_ajax():
        message = "This is ajax"
    else:
        message = "Not ajax"
    return HttpResponse(message)

urls.py:

urlpatterns = [
    path('', views.index, name='index'),
    path('save_events_json/', views.save_events_json, name='save_events_json'),
]

What is the essence of the problem. After clicking on the save_walls button, the alert “This is ajax” is displayed, but after closing the alert and going to the save_events_json page, it says “Not ajax”, what is the problem?

Please format your examples nicely in future posts, so they are readable by people trying to help you.

As I understand what you’re seeing is the exact documented behaviour of is_ajax: https://docs.djangoproject.com/en/3.0/ref/request-response/#django.http.HttpRequest.is_ajax

Note that is_ajax will actually be deprecated in Django 3.1: https://code.djangoproject.com/ticket/30997 . You should consider making separate views for AJAX versus non-AJAX.

1 Like

Thanks. Can you write how to more correctly pass an array or variable from JS to django. Can ajax be avoided at all?

I’m not sure what problem you’re trying to solve. What are you trying to do?

AJAX can be avoided if it’s only when the page loads: https://adamj.eu/tech/2020/02/18/safely-including-data-for-javascript-in-a-django-template/

Otherwise for AJAX views you should look at JsonResponse: https://docs.djangoproject.com/en/3.0/ref/request-response/#jsonresponse-objects . Or for more advanced usage, see Django REST Framework.

I am trying to transfer an array from JS to Django, for this I was thinking of using ajax. But maybe there are still ways, I don’t know, therefore I ask for advice.

OK, well the code you have shown is the beginnings of that, except I’d maybe use POST instead of GET for saving the data in the JavaScript snippet. What is surprising you about the result you have described?

I used Get because it only worked, which is strange. There is a page with a button, after it is pressed, alert appears with the message that need. That is, the function in django saw that ajax worked. But when loading a new page after clicking OK on alert, django the function returns that ajax did not work, how is it?