Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send data from javascript function to Django View

I am trying to send data from a javascript function that generates a random string upon the page loading to a Django view. I don't know how to structure the script tag to send the data after the page has loaded and the views.py to receive the data. I am new to javascript and don't quite know how to go about this. I appreciate any help provided.

index.html

<script>

    function makeid(length) {
        var result           = '';
        var characters       = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        var charactersLength = characters.length;
        for ( var i = 0; i < length; i++ ) {
            result += characters.charAt(Math.floor(Math.random() * charactersLength));
        }
        return result;
    }
    console.log(makeid(9));

</script>
like image 253
AllanM007 Avatar asked Oct 29 '25 10:10

AllanM007


1 Answers

You can use ajax to send data to Django view like following code.

javascript:

function makeid(length) {
    var result           = '';
    var characters       = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var charactersLength = characters.length;
    for ( var i = 0; i < length; i++ ) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }
    $.ajax({
        type: "GET",
        url: '/my_def_in_view',
        data: {
            "result": result,
        },
        dataType: "json",
        success: function (data) {
            // any process in data
            alert("successfull")
        },
        failure: function () {
            alert("failure");
        }
    });
}

urls.py:

urlpatterns = [
               url(r'^my_def_in_view$', views.my_def_in_view, name='my_def_in_view'),
               ...
]

views.py:

def my_def_in_view(request):
    result = request.GET.get('result', None)
    # Any process that you want
    data = {
            # Data that you want to send to javascript function
    }
    return JsonResponse(data)

If it was successfull it goes back to "success" part.

like image 93
Majid A Avatar answered Oct 31 '25 00:10

Majid A



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!