0

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.

Community
  • 1
  • 1
user1919
  • 3,818
  • 17
  • 62
  • 97
  • So what isn't working? – Sayse May 31 '16 at 13:53
  • Right now I haven't implemented an ajax request. When I click on the button I want the view to get executed without redirecting my page. – user1919 May 31 '16 at 14:01
  • 1
    Then what are you asking for help on? It's clear you know how to use jQuery; why don't you just write a `$.get()` call in that event handler? – Daniel Roseman May 31 '16 at 14:04
  • Thanks. My issue is not the $.get(). I have problems understanding if I should include my new view in the urls.py file as: url(r'^what_to_put_here???$', 'test_download', name='test_download') – user1919 May 31 '16 at 14:06
  • 1
    Possible duplicate of [How do I integrate Ajax with Django applications?](http://stackoverflow.com/questions/20306981/how-do-i-integrate-ajax-with-django-applications) – Dhia May 31 '16 at 14:43
  • 1
    Again, I don't understand what you're asking. There is no mention of a template in your view, so it won't be returning an error about missing templates. And the URL can be whatever you want it to be; since you're generating that dynamically using the `url` tag, it makes no difference what the actual path is. But all of this is absolutely basic Django, and has nothing whatsoever to do with Ajax; an Ajax request is exactly the same as any other request from Django's point of view. – Daniel Roseman May 31 '16 at 14:49
  • 1
    @user1919 Yes you must add your view to your urls.py file, or django will have no way of dispatching the request to the correct view (request response loop). As Daniel Roseman has pointed out, it doesn't matter what the path is, since you're namespacing your urls and calling the url with the url template tag. Just make sure it's unique. I'd also like to point out that you have a typo in your urls.py file. 'test_download' is spelled incorrectly (for both the view name and the url name), which is the cause of the no reverse match error. Unless you just have a typo on SO – Curtis Olson May 31 '16 at 15:44

1 Answers1

3

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

M. Gar
  • 889
  • 4
  • 16
  • 33