Calling PHP function file_put_contents from inside jQuery

I have a function inside jQuery when a PHP function is called when the condition is met. Everything is going well until I can file_put_contents. It seems like it should produce some kind of output that jQuery does not know how to interpret. Here is my code:

Part of jQuery where $ downloader is an instance of a class and complete. Download is a javascript variable:

if (finishedDownloading==<?php echo $downloader->_totalFiles ?>){ <?php $downloader->MergePDFs(); ?> } 

So far so good. And here is my php:

  function MergePDFs() { $combinedFiles = ""; foreach ($this->_fileNamesArray as $filename) { $combinedFiles .= file_get_contents($filename); //these are the urls of my files } echo "document.getElementById('test-if-finished').innerHTML = 'Test output: " . $this->_file . "'"; // this is for testing //The above code works, the problem comes when I add the lines below file_put_contents("all-files.pdf", $combinedFiles); 

If I comment out the lines of file_put_contents, everything goes smoothly.

If I uncomment when I run the code, I get a crazy "uncaught referenceError" error stating that my JQuery function is undefined.

Can someone tell me what's going on?

thanks

Edit: I think file_put_contents returns some value that jQuery does not know what to do.

Edit 2: This cannot be done, even if I was able to get rid of the jquery error, the function will execute when the page loads, not taking into account the if statement

+5
source share
1 answer

In the jQuery part, you should not call PHP functions by including them in javascript code. In your example, the PHP code will be processed in any case if the condition of the if jQuery component does not occur or not.

Try something similar for jQuery:

 if (finishedDownloading==<?php echo $downloader->_totalFiles ?>){ $.get('mergepdf.php'); } 

And mergepdf.php, like your code:

 <?php function MergePDFs() { $combinedFiles = ""; foreach ($this->_fileNamesArray as $filename) { $combinedFiles .= file_get_contents($filename); //these are the urls of my files } echo "document.getElementById('test-if-finished').innerHTML = 'Test output: " . $this->_file . "'"; // this is for testing and works fine file_put_contents("all-files.pdf", $combinedFiles); ... } MergePDFs(); 
+2
source

Source: https://habr.com/ru/post/1243113/


All Articles