[Answer]-Django – passing data from server to js function via class based view

1πŸ‘

βœ…

1.
Create a javascript/jquery function in your view which makes an $.ajax({options}); call to the url you want to send & receive data from (See #4 for an example).

2.
Have your views.py file import the json & HttpResponse module.

import json
from django.http import HttpResponse

3.
Add a function in your views.py to handle the request

def ExampleHandler(request):

Within this function, you can access parameters like request.POST[β€˜paramname’] or request.GET[β€˜paramname’]. See https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.GET for more information.

To return data to the ajax call, store your data in a dictionary like this:

result = {
    'success': True,
    'foo': bar,
    'more': data
}

and return the json like this:

return HttpResponse(json.dumps(result), content_type="application/json")

4.

Your original javascript function will look similar to this now:

function exampleRequest() {
    $.ajax({
        type: 'POST',
        url: '/url-mapped-to-your-view',
        data: {data: 'some-data-to-send-to-views'},  // May need to add a CSRF Token as post data (eg: csrfmiddlewaretoken: "{{ csrf_token }}")
        error: function() {
            alert('There was an issue getting the data...');
        },
        success: function(data) {
            // Accessing data passed back from request, handle it how you wish.
            alert(data.foo);
            alert(data.more);
        }
    )};
}

5.
Ensure the url you make the ajax call to is correctly mapped in urls.py

πŸ‘€ljlozano

0πŸ‘

You can probably pass data via args or kwargs

in views.py

class YourView(TemplateView):

    def get_context_data(self, **kwargs):
        context = super(YourView, self).get_context_data(**kwargs)
        context['yourdata'] = self.kwargs['data']
        return context

in urls.py

url(r'(?P<data>\w+)$', YourView.as_view()),
πŸ‘€maremare

Leave a comment