WordPress.org

Ready to get started?Download WordPress

Forums

Using WordPress Ajax API to download a file? (1 post)

  1. fireproofsocks
    Member
    Posted 2 years ago #

    I've successfully implemented the "AJax best-practices" from this article:
    http://www.garyc40.com/2010/03/5-tips-for-using-ajax-in-wordpress/

    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.
    http://mysite.com/wp-content/plugins/my-plugin/ajax/my_controller.php

    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() {
    	jQuery.post(
    	    MyObject.ajax_url,
    	    {
    	        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:

    <?php
    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?

Topic Closed

This topic has been closed to new replies.

About this Topic

  • RSS feed for this topic
  • Started 2 years ago by fireproofsocks
  • This topic is not resolved
  • WordPress version: 3.2.1