Skip to content
Advertisement

Using JavaScript Onclick Event to pass Data to views.py in Django?

I Have a bit of idea about this to use ajax with the JavaScript to send data to views.py but I am not able to do that.

So what I am trying to do is I have put onclick event on the image so by clicking on that image I should be able to send some value to views.py.

This is Hello.html file:

<img src="" onclick="change()">

JavaScript function:

function change(){
     // Do something here to send data to views.py
 }

Now in views.py

def SomeFunction():
    //To get data here
    

Advertisement

Answer

You can use ajax function :

Template:

<img src="" onclick="change(foo, bar)">

javaScript :

function change(foo, bar){
    $.ajax({
        url: 'ajax/foo/',
        data : {
            'foo': foo,
            'bar': bar
        },
        success: function (data) {
            $("#idImg").html(data);
        }
    });
}

views.py :

def SomeFunction(request):
foo = request.GET.get('foo')
foo = request.GET.get('bar')
...

urls.py

path('ajax/foo/', views.SomeFunction, name='ajax_foobar'),
Advertisement