7

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.

1 Answers1

17

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")
Henrik Andersson
  • 45,354
  • 16
  • 98
  • 92
  • Thank you SO much for the clear answer! One question: what should my url contain? Do I have to make a new one and specify it in urls.py or is it just the same as my homepage? – Anne McLaughlin Nov 11 '14 at 21:53
  • Yeah, you should. You need to map it against a view so that you can take care of the ajax call. Not specifying an URL will cause it yo submit to the same URL you're currently on, much like a normal form submit. – Henrik Andersson Nov 12 '14 at 06:41