Javascript for Django views.py?

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

When the user clicks the "Recommend" button, my code calls a function that accesses my database and prints the name in 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 computed after the user clicks Recommend. I want to send it to my index and use it as a parameter to 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 looking for similar questions, but I'm new to Django and web development in general, so either I didn't understand the answers or they didn't help me.

+3


source to share


1 answer


Ok, so to send data from the client (JavaScript) to the backend (your Django app), you need to use something called Ajax, that means asynchronous JavaScript and XML. Basically what it does is allow you to communicate with your backend services without having to reload the page, which you would need to do using a normal POST or PUT form submission.

The simplest implementation uses jQuery . jQuery is primarily a DOM manipulation library, but has grown since its inception to cover a lot more.

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 in views.py

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

      

+12


source







All Articles