user1919
user1919

Reputation: 3938

How to make an ajax request to a view

I am trying to figure out how I can make an ajax request (with jquery) from my template in order to execute a view on a button click. I don't want to redirect to another page. I just need to execute the code in the view.

This is my on button click event:

$(document.body).on("click", "#download_xls",function(e) {
        selected_country = ($("#button-countries").val())
        selected_subareas = $('#_all_values').val();
        id = "?country=" + selected_country + "&" + "regions=" + selected_subareas
        whole_url = "{% url 'test_download' %}" + id
        $("#download_xls").attr("href", whole_url)
    });

As I pass the values in my URL, I don't even need to pass some parameters through the ajax request. I just need to execute the code in the view.

The view is something like this:

def test_download(request):
    print(request.GET.get('country'))
    print(request.GET.get('regions'))

    fileContent = "Your name is %s"
    res = HttpResponse(fileContent)
    res['Content-Disposition'] = 'attachment; filename=yourname.txt'
    return res

EDITED

I have added the ajax GET request in my template as:

       whole_url = "{% url 'test_download' %}"+id
       $.ajax({
            type: "GET",
            url: whole_url,
            success: function(data) {
                alert('sd')
            },
            error: function(data) {
                alert('error')
            },
        });

I get an error cause there is no corresponding template for this view. I think I need to add something in the urls.py file.

I read here that I need to modify urls.py as:

url(r'^link-to-fun1$', views.fun1),

But its not clear to me what should be the link-to-fun1. I tried:

 url(r'^create$', 'test_download', name='test_downlad'),

But gives an error: No Reverse Match.

Upvotes: 0

Views: 3477

Answers (1)

M. Gar
M. Gar

Reputation: 887

You could use TemplateView add to your url and use JQuery to do something, like this:

views.py

class ajax_view(TemplateView):
    def get(self, request, *args, **kwargs):
            id_value = request.GET['id']
            value = Model.objects.filter(id=id)
            data = serializers.serialize('json', value, fields=('fieldone'))
            return HttpResponse(data, content_type='application/json')

urls.py

url(r'^ajax/$', ajax_view.as_view()),

JQuery

$.ajax({
            data: { 'id': id },
            url: '/ajax/',
            type: 'get',
            success: function (data) {
                // Do something with the data
            }
        })

That's in general how you can use Ajax with Django, the important is the use of TemplateView

Upvotes: 3

Related Questions