[Django]-How pass javascript function 's value to Django view?

3👍

Hi the trick to sending data back is to send POST request back to the server.

Im going to use JQuery as an example to do so (since it is so much faster and easier)

$.ajax({
    // points to the url where your data will be posted
    url:'/postendpoint/$',
    // post for security reason
    type: "POST",
    // data that you will like to return 
    data: {stock : stock},
    // what to do when the call is success 
    success:function(response){},
    // what to do when the call is complete ( you can right your clean from code here)
    complete:function(){},
    // what to do when there is an error
    error:function (xhr, textStatus, thrownError){}
});

Then you will have to adjust your apps’ urls.py to match your postendpoint and point it to the correct view for instance

##urls.py
urlpatterns = [
    url(r'^postendpoint/$', views.YourViewsHere),
    ....
] 

and finally your in your views you can access the post data like this

##views.py
def YourViewsHere(request):
   if request.method == 'GET':
       do_something()
   elif request.method == 'POST':
       ## access you data by playing around with the request.POST object
       request.POST.get('data')

as you can request is a python object there are many attributes and methods that you can look at.

For more info look at

1) Django request-response https://docs.djangoproject.com/en/1.7/ref/request-response/
2) Django Ajax exmple :How do I integrate Ajax with Django applications?

Note that you will have to play around with the code that I gave you. I think it will be the best way to learn from there.

I hope you find this useful

Leave a comment