Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to open a PDF file while returning the file in AJAX request success response

I get 2 dates, start and end date, via AJAX. I process the data b/w those 2 dates, generate a report and then returns an HttpResponse. The PDF report is now saved in my main project directory. Now I get a response back in AJAX. So, now how should I process the response in the success function, sent back from the sever and open a PDF file.

Thanks.

jQuery

$(function() {
  $("#report_submit").click(function(){
      $.ajax({
      type : "POST",
      url: "/reports/",
      data : { 'start_date' : $("#startDate").val() , 'end_date' : $("#endDate").val() },
      success : function(result){

      },

      error : function(result){
      }
    });

  });
});

Django view code

def generate_report(request):
    ctx = {}

    if request.is_ajax():
        if request.POST.has_key('start_date'):
            start_date = datetime.strptime(request.POST[ 'start_date'] , '%m/%d/%Y')
            end_date = datetime.strptime(request.POST[ 'end_date'] , '%m/%d/%Y')

            ......
            # PDF GENERATED in MAIN PROJECT DIRECTORY

            with open(os.path.join(os.path.dirname(__file__),'../../../../gui','Report.pdf')) as pdf:
                response = HttpResponse(pdf.read(), content_type='application/pdf')
                response['Content-Disposition'] = 'inline;filename=Report.pdf'

                return response  # so, now when I send a response back, how should I process it in AJAX success function?
            pdf.closed


    return render(request, 'generate_report/reports.html', ctx)
like image 372
PythonEnthusiast Avatar asked Dec 09 '13 09:12

PythonEnthusiast


People also ask

How can I open PDF file in ajax?

cshtml for open a PDF in new tab or download the PDF using the Ajax Call. var pdfData = new Uint8Array(num); //var blob = new Blob([pdfData], { type: 'text/plain' }); blob = new Blob([pdfData], { type: 'application/pdf;base64' });

How can download PDF with button click in jQuery?

Downloading PDF File on Button Click using jQueryInside the DownloadFile JavaScript function, the URL of the File is passed as parameter to the jQuery AJAX function. Inside the jQuery AJAX function, using the XmlHttpRequest (XHR) call, the PDF file is downloaded as Byte Array (Binary Data).

What does ajax request return?

ajax() (and various ajax shortcut methods) returns a jqXHR object, which is a superset of the browser's native XMLHttpRequest object and implements inter alia the Promise interface.


1 Answers

Don't try and send it in the Ajax response. Instead, get your view to generate a unique URL for the PDF, then get the JS to redirect the browser to that URL:

view:

return HttpResponse(json.dumps({'url': my_url})

JS:

$.ajax({
  type : "POST",
  dataType: "json",
  url: "/reports/",
  data : { 'start_date' : $("#startDate").val() , 'end_date' : $("#endDate").val() },
  success : function(result){
     var url = result['url'];
     window.location = url;
  },
like image 127
Daniel Roseman Avatar answered Sep 21 '22 10:09

Daniel Roseman