Home » Jquery » asp.net mvc – jQuery event after a PDF loads?

asp.net mvc – jQuery event after a PDF loads?

Posted by: admin February 22, 2020 Leave a comment

Questions:

I have a modal dialog that allows users to generate a customized PDF. After they click a “Start” button, the page redirects with window.location to a controller, which then creates the PDF and returns it.

Because of how long it takes the PDF to return, I want to display a modal “Generating PDF” dialog that automatically closes once the PDF is complete and is returned.

The problem is I can’t figure out how/when to execute that final function to close the “Generating PDF” dialog. Since the controller returns an application/pdf type, there is no document object event to attach to, right? What is the best way to do this?

How to&Answer:

This is how I would do it

  1. User clicks the link to create the pdf

  2. An AJAX request is sent to server to generate pdf

  3. Server adds the pdf creation to background job and returns the
    status as added

  4. Client receives the status, shows the model or animation and start pinging the
    server every 3 seconds for status

  5. Server returns the status after (n) seconds as completed/failed and a link to the
    pdf

  6. Client hides the model/animation, stops the ping and open the link in new tab which will
    download the pdf

Answer:

Thank you for your responses. @PGill was on the right track. I’ve simplified his approach:

  1. User clicks the Start button
  2. The “Generating PDF” modal dialog is displayed
  3. An AJAX request is sent to Controller 1 to generate the PDF
  4. Controller 1 creates the PDF (which takes 5-60 seconds), stores it in a secure location, and returns a unique key
  5. The “Generating PDF” modal dialog is hidden
  6. The browser is redirected to Controller 2 and sent the unique key
  7. Controller 2 verifies the key, retrieves the PDF from the secure location, and returns it

The solution here was to separate the Generation of the PDF from the Download of the PDF into 2 steps, so that between them, the modal dialog can be hidden.

which verifies it, retrieves the PDF rom the secure location and returns it.

ShowModalDialog();

$.ajax({
  type: "GET",
  url: 'GeneratePDFReportForDownload?' + params,
  success: function (pdfkey, textStatus, jqXHR) {
      HideModalDialog();
      window.location = 'DownloadPDFReport?key=' + pdfkey;
  },
  async: true,
  datatype: 'json'
});

Answer:

redirect to a controller, that creates your pdf and saves it. the controller should return after saving the pdf a js that closes the modal and redirects to another control, that only reads and response the pdf file.