[Answered ]-Django How to call a function in views.py from ajax by clicking submit button with variable

1👍

You have to use JsonResponse(Django Docs) in your view myajaxtestview.

from django.http import JsonResponse

def myajaxtestview(request):
    input = request.POST.get('msg')
    return JsonResponse({"message": "My Ajax Test", input: input})

AJAX:

msgerForm.addEventListener("submit", event => {
    ...
    botResponse($(this).serialize());
});

function botResponse(data) {
    $.ajax({
        url: "{% url 'ajaxview' %}",
        method: 'POST',
        data: data,
        success: function (response) {
            appendMessage(PERSON_NAME, PERSON_IMG, "left", response.message);
        },
    });
}

Urls.py:

path('ajax-test-view/', views.myajaxtestview, name='ajaxview')

Add jQuery:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
👤NKSM

Leave a comment