简体   繁体   中英

Call php file which return PDF with jQuery AJAX function

My php file: example_061.php create PDF return and everything works fine.

Now I want to call that file with jQuery AJAX to get this at my screen and I try:

$("#proba").click(function() {
  //in here we can do the ajax after validating the field isn't empty.
  $.ajax({
    url: "tcpdf/examples/example_061.php",
    type: "POST",
    async: true, 
    data: { 
      ime: $("#ime").val(),
      pozicija: $("#pozicija").val(),
      jmbg: $("#jmbg").val()
    }, //your form data to post goes here as a json object
    dataType: "html",
    success: function(response) {
      window.open('example_061.pdf');
    },  
  });        
});

Everything is fine so success function work an I get alert message but I don't get PDF file as download or at screen. How I can do that?

You do not need to use AJAX to download a file. If the content-disposition header is set, it will be downloaded and the current page will not be reloaded.

Just add this to your php script that creates the PDF:

header('Content-Disposition: attachment; filename=' . $MyFileName); 

And instead of AJAX, use a regular anchor tag link:

<a href="tcpdf/examples/example_061.php">Download</a>

As someone noted in the comments, if you need to post you can still use a simple form with the same effect:

<form method="POST" ACTION="tcpdf/examples/example_061.php">
<input type="hidden" name="myPostItem" value="My POSt VALUE" />
<input type="submit" value="download">
</form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM