I have populated a multi-dimensional PHP array using a function and I wish to allow my admin users to download the content.
I've found a PHP function which should allow me to export an array to CSV and put it in my functions.php, used a second function to hook it to AJAX and used jQuery to fire the AJAX function.
What's the problem?
So I am 99% sure the AJAX correctly posts to the PHP function, but for some reason the download isn't being started.
I've researched this a lot but struggling to find a solution - would really appreciate a point in the right direction!
// Function to generate download
function convert_to_csv( $input_array, $output_file_name, $delimiter ) {
/** open raw memory as file, no need for temp files, be careful not to run out of memory thought */
$f = fopen( 'php://memory', 'w' );
/** loop through array */
foreach ( $input_array as $line ) {
/** default php csv handler **/
fputcsv( $f, $line, $delimiter );
}
/** rewrind the "file" with the csv lines **/
fseek( $f, 0 );
/** modify header to be downloadable csv file **/
header( 'Content-Type: application/csv' );
header( 'Content-Disposition: attachement; filename="' . $output_file_name . '";' );
/** Send file to browser for download */
fpassthru( $f );
}
And I've hooked it to Wordpress AJAX using another function
function laura_function() {
$input_array = $_POST["inputarray"];
convert_to_csv($input_array, 'output.csv', ',');
exit;
}
add_action('wp_ajax_nopriv_ajaxlaurafunction', 'laura_function');
add_action('wp_ajax_ajaxlaurafunction', 'laura_function');
And I've written a little jQuery Function to make the AJAX call on button click
<button type="button" id="downloadcsv">Download CSV</button>
<script>
jQuery(document).ready(function () {
jQuery('#downloadcsv').click(function () {
var data = {
action: 'ajaxlaurafunction', // Calls PHP function - note it must be hooked to AJAX
inputarray: '<?php echo $inputarray?>', // Sends a variable to be used in PHP function
};
// This is a shortened version of: https://api.jquery.com/jquery.post/
jQuery.post("<?php echo admin_url('admin-ajax.php'); ?>", data, function () {
//window.location.replace(location.pathname)
});
});
});