-1

I have a javascript array that I need to send to a PHP page to create PDF files on the fly.

I have the array, and I have the PDF creation working, but I can't figure out how to get the javascript array to a PHP array so I can just use a foreach loop to get the values.

Ajax won't work because the PDF file comes back as data and not a file. I can load the PHP file into an iframe, but I'd have to pass the array with a query string.

Is there a way to just pass the array to the PHP page (I can either reload the page the user is on or link to another page) intact through post?

jQuery or vanilla JavaScript is fine.

  • Use JavaScript to create a `
    ` element, populate an ``, and submit it to your PHP file.
    – Niet the Dark Absol Sep 20 '17 at 17:02
  • You just convert the array into json and use ajax api. For more info use the link https://stackoverflow.com/questions/8517071/send-json-data-via-post-ajax-and-receive-json-response-from-controller-mvc. It may helpful for you. – Jino Shaji Sep 20 '17 at 17:03
  • 1
    @JINOSHAJI The OP have already stated: _"Ajax won't work because the PDF file comes back as data and not a file."_ – M. Eriksson Sep 20 '17 at 17:11

1 Answers1

0

I have solved this. I'm not sure why it works the way it does, but it's working. I've added a form with a hidden field, and I'm putting the array into that field. Then I'm submitting the form:

$("#pdfArray").val(JSON.stringify(pdfs)); $("#pdfarrayform").submit();

Then I'm just decoding it on the PHP file:

$pdfArray = json_decode($_POST['pdfArray']);

It all works without actually leaving the original page. The PDF file downloads and the user is left on the form page, which makes it look like ajax, but it's not.

  • That is quite common behavior, for example when you press on a link to a ZIP file the browser download it without leaving the page, this is similar but with a PDF and a form instead of just a link. – Alberto Martinez Sep 20 '17 at 23:59
  • I suppose it is. Except that it's going to a PHP page which is creating a PDF on the fly. Normal behavior would be to go to the PHP page and stay there. Right? – Keith Homel Sep 22 '17 at 00:27
  • You are associating a PHP page with an HTML output, and while it's the most common case is not the only one, a PHP script can return binary data (a lot of sites use PHP or another server language to serve binary files). Note that the way the browser process a URL depends on the `Content-Type` of the response header, not the file extension (in fact, if you are returning binary data and forget to change the type in the header the browser would display the binary data instead of handling it to the appropriate plugin or external app). – Alberto Martinez Sep 22 '17 at 00:42