Quantcast
Viewing all articles
Browse latest Browse all 59525

How do I send a file to download with AJAX in WordPress?

Replies: 0

Hello!
I’m trying to cut the plugin for WordPress. Help, who than can, please 🙂
The JavaScript data is taken from the backend and returned to PHP, which creates a file on the server. The task is to give it to the user in the browser. Old script gave it without problems download.php:

header('Content-Description: File Transfer');
header('Content-Type: application/force-download');
header('Content-Disposition: attachment; filename='$name;');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($name));
if (ob_get_contents()) ob_end_clean();
flush();
readfile($name);

But for security, you must prohibit direct access, OK:
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
Accordingly, the call to AJAX hung on success began to open an empty window:

$.ajax  (
        {

        type: "POST",

          url: myAyax.ajax_urls.write_url ,//Here, the function hooked via the hook to admin-ajax.php is called

        data: {
          ids:arr, //This is some kind of data

          action: 'write_file_server', //We pass the hook. Who writes a file with data to the server.

                },
      success: function(result){

          window.location = myAyax.ajax_urls.download_url //Here was a link to the direct call download.php (see above)
          })

        }

      });

Tried to cause, in function caused through a hook: include (‘download.php’);
Called, sends the contents and code to the buffer 200, but does not swing;)
The link in succes-e on the file opens its contents, and also does not swing, of course 🙂
Help ideas, please.


Viewing all articles
Browse latest Browse all 59525

Trending Articles