Skip to content
Advertisement

Javascript to Django views.py?

This may sound simple, but how do I send the data from a Javascript array in my index.html template to my views.py?

When the user clicks a “Recommend” button, my code calls a function that accesses my database and prints a name on the template.

def index(request):
    if(request.GET.get('Recommend')):
        sql_handler.recFunc()
        context['name'] = sql_handler.name
        return render(request, 'polls/index.html', context)

I have an array of checkbox values in Javascript that are calculated after the user presses “Recommend”. I want to send it to my index view and use it as the parameter for another function.

So:

def index(request):
    if(request.GET.get('Recommend')):
        sql_handler.recommend()
        context['name'] = sql_handler.name
        //something??
        tags = check_array_javascript
        context['tags'] = tags
        return render(request, 'polls/index.html', context)

How can I do this? I’ve been searching similar questions, but I’m new to Django and web development in general, so I either did not understand the answers or they didn’t help me.

Advertisement

Answer

Alright, so for sending data from the client (JavaScript) to the backend (your Django app) you need to employ something called Ajax, it stands for Asynchronous JavaScript and XML. Basically what it does is allowing you to communicate with your backend services without the need of having to reload the page, which, you would have to do using a normal POST or PUT form submission.

The easiest implementation is using jQuery. jQuery is first and foremost a DOM manipulation library but since its inception has grown to encompass much more than that.

A jQuery ajax call looks like this.

$(document).ready(function() {
    $.ajax({
        method: 'POST',
        url: '/path/to/your/view/',
        data: {'yourJavaScriptArrayKey': yourJavaScriptArray},
        success: function (data) {
             //this gets called when server returns an OK response
             alert("it worked!");
        },
        error: function (data) {
             alert("it didnt work");
        }
    });
});

This can then be checked for in your views.py

def index(request):
    if request.is_ajax():
        #do something
        request_data = request.POST
        return HttpResponse("OK")
Advertisement