0

I need to send a JavaScript variable to the view and based on that variable,a new page opens.I've send the variable using ajax and it works well but when I call the URL to open the page based on sent variable,the variable gets None value. Here is my template :

<a onclick="click(this.id)" id="author[i].name" href="{% url 'app:export-pdf' %}" >export pdf</a>

author[i].name is the JavaScript variable that I send it to view in this way :

function click(name){
  $.ajax({
    type: 'POST',
    url: '{% url 'app:export-pdf' %}',
    data: {'name': name },
  });
};

This is part of my view if needed :

@csrf_exempt
def battery_render_pdf_view(request):
    name = request.POST.get('name')
    print(name)
    data = MyModel.objects.filter(name=name)

When I run the code, I'll get for example :

Mike
None

The view get None as name but it must get Mike for filtering. What is wrong with my code?(I think it happens because I call the Url 2 times but I didn't find out how to correct it.)

Thank you all.

Farzan
  • 198
  • 2
  • 11
  • dont include url tag in anchor tag. also in ajax, use just a path to the url like '/exportpdf' and not the url tag. – Rahul Oct 21 '20 at 10:04
  • @RahulSalgare I've changed my ajax url but without including url tag in anchor tag,how could I make the anchor tag opens the new page?thanks. – Farzan Oct 21 '20 at 10:17
  • try returning true. see here https://stackoverflow.com/questions/1346043/html-anchor-link-href-and-onclick-both. You can also change window location in ajax after successful request call. – Rahul Oct 21 '20 at 10:23

1 Answers1

1

Finally I have found a simple way like below :

template :

<a href="the path you want/{{this.id}}" id="author[i].name">export pdf</a>

url :

path('pdf/<int:authorid>/', pdf_view, name='pdf-data')

and in view , you can access authorid by using kwargs:

def pdf_view(request,**kwargs):
    author = kwargs.get('authorid',None)
    data = MyModel.objects.filter(name=author)
Farzan
  • 198
  • 2
  • 11