[Django]-How to pass javascript variable value to views.py function in django?

6πŸ‘

βœ…

The easiest way is probably to just build an AJAX query. Try something like this:

<script type="text/javascript">
    $(document).ready(function() {
        var url = data.result.docs[i].source.enriched.url.url;
        $("#send-my-url-to-django-button").click(function() {
            $.ajax({
                url: "/process_url_from_client",
                type: "POST",
                dataType: "json",
                data: {
                    url: url,
                    csrfmiddlewaretoken: '{{ csrf_token }}'
                    },
                success : function(json) {
                    alert("Successfully sent the URL to Django");
                },
                error : function(xhr,errmsg,err) {
                    alert("Could not send URL to Django. Error: " + xhr.status + ": " + xhr.responseText);
                }
            });
        });
    });
</script>

Assuming you have a button on your page like this:

<button type="button" id="send-my-url-to-django-button">Send URL to Django View</button>

Clicking that button should send the url to your Django view. Then on the Django side, you can access the url like so:

def process_url_from_client(request):
    url = request.POST.get('url')
πŸ‘€Dirty Penguin

0πŸ‘

Yes you can use anchor tag only, but in that case you will send data like this
http://host/path_to_view.py/urlValueToSend.
This will be a simple get request and url will be sent to the server
You may need ro encode the url as it contains special characters

var val = EncodeURI(url);

Leave a comment