Support » Plugins » Hacks » Using WordPress Ajax API to download a file?

  • I’ve successfully implemented the “AJax best-practices” from this article:

    One of my Ajax handlers is supposed to force the download of a file. The controller works fine if you navigate to it directly, e.g.

    But when I request it via the WordPress API, the controller returns the correct data, but something doesn’t work correctly that way. I suspect that the WP ajax handler is printing its own headers (?) and ignoring mine.

    I’m using the wp_localize_script to pass the URL to my Ajax controller (as described in the above article), and that’s working.

    The request is triggered via Javascript like this:

    jQuery(document).ready(function() {
    	        action : 'download_def',
    	    function( response ) { console.log(response); }

    The controller file prints a bunch of headers to trigger the download, and then prints the payload text. Something like this:

    header("Content-Type: application/force-download");
    header("Content-Disposition: attachment; filename=myfile.txt");
    header("Content-length: ".(string) mb_strlen($payload, '8bit') );
    header("Expires: ".gmdate("D, d M Y H:i:s", mktime(date("H")+2, date("i"), date("s"), date("m"), date("d"), date("Y")))." GMT");
    header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
    header("Cache-Control: no-cache, must-revalidate");
    header("Pragma: no-cache");
    print $payload;

    When I check the console in firebug, the payload is entirely correct, but the download isn’t triggered unless I access the controller file directly, outside of the WP Ajax API.

    Anyone have any pointers here?

  • The topic ‘Using WordPress Ajax API to download a file?’ is closed to new replies.