Plamen
Plamen

Reputation: 390

jQuery loads cached file inside ajax success function

I am trying to create a file (pdf from TCPDF) and to load it in an embed object on my page using Ajax request to a php file:

$.ajax({
  url: 'my_file_which_create_pdf_file.php',
  type: 'POST',
  success: function(){
      $('#pdf_placeholder embed').attr('src','output/my_file.pdf');
      },
  error: function (xhr, status, error) {
      if (xhr.status > 0) {
          alert('got error: ' + status);
          }
      }
  });

This is my html code:

<div id="pdf_placeholder">
    <embed id="pdf_document" src="" width="900">
</div>

This is working, but... sometimes (usually after correcting errors in php file) embed object is loaded with a cashed version of the pdf file, not with the freshly generated.

I delete the file, invoke the script, pdf file is generated properly, (checked it through ftp client), but embed object loads the older version of the pdf file.

Adding async: false, in Ajax request change nothing, still cashed pdf file is showing.

Upvotes: 0

Views: 476

Answers (2)

M Khalid Junaid
M Khalid Junaid

Reputation: 64466

Have you tried to turn off ajax cache which is by default true

$.ajax({
url: 'my_file_which_create_pdf_file.php',
type: 'POST',
cache: false,
success: function(){
  $('#pdf_placeholder embed').attr('src','output/my_file.pdf');
  },
error: function (xhr, status, error) {
  if (xhr.status > 0) {
      alert('got error: ' + status);
      }
  }
});

jQuery.ajax

Upvotes: 0

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123377

try to use a simple cachebusting technique, like

$('#pdf_placeholder embed')
     .attr('src', 'output/my_file.pdf?v=' + Math.random());

this will always invalidate the cache for the pdf

Upvotes: 1

Related Questions