Jump to content

Create downloadable CSV file using AJAX question(s)


maxxd

Recommended Posts

Hey y'all. I've dug around on SO and other sites, and pretty much everything I'm finding is making me think that what I'm doing here should be working. Problem being, it's not. First, a little background.

 

I'm trying to create a CSV export of a WordPress back-end report that I've built and have had working for a bit now. I'm using AJAX to gather the data for both the display and the export. So, the user selects a date range, clicks 'Go', and the system uses AJAX to populate the report data into the table as expected. At this point, the user can click the 'Export' button, and - theoretically - once again the page uses AJAX to gather the data and display a 'Save as...' window with the newly generated report.

 

My PHP code:

public function exportReportData(){
	$data = $this->gatherReportData(false);
	$tmp = tempnam(sys_get_temp_dir(), 'your_csv_dl');
	if($tmp === false || !file_exists($tmp)){
		print(json_encode(array('success',false)));
		exit;
	}
	$fileName = 'report_'.(new \DateTime())->format('Ydmhis').'.csv';
	$handle = fopen($tmp,'w');
	foreach($data as $row){
		fputcsv($handle,$row);
	}
	fclose($handle);
	header('Content-Description: File Transfer');
	header('Content-Type: text/csv');
	header('Content-Disposition: attachment; filename='.$fileName);
	header('Expires: 0');
	header('Cache-Control: no-cache must-revalidate');
	header('Pragma: public');
	header('Content-Length: '.filesize($tmp));
	readfile($tmp);
	unlink($tmp);
	exit;
}

The system outputs the expected data - I can view it in my console. However, it doesn't pop up the expected 'Save as...' dialog, and I have no idea why. I've tried Content-Type: application/octet-stream, text/csv, application/csv, and a couple others that I can't remember right now.

 

So, a couple questions - first off, the obvious. Does anyone see anything in the code above that's causing it to not work as expected? Did I leave something out, use the wrong value for a header, name something incorrectly, anything at all? Secondly, if I'm creating the file in the server temp directory, is it necessary to unlink() it at the end of the script, or will garbage collection take care of it on it's own?

 

Any and all help is much appreciated, and thanks for taking the time to take a look.

Link to comment
Share on other sites

Thanks guys (or gals, not sure).

 

The thing is, I've seen this method work for a dynamically created .zip file before, and can't quite figure out why it's not doing anything for a CSV. I'll give a shot to the redirect method, which hopefully will work in WP. And thanks much for the heads-up on the output stream. I'm not terribly excited about the prospects of writing and deleting a file on the server every time my client wants to export the data, so that'll put my mind at ease a bit!

Link to comment
Share on other sites

Javascript can't save files to your computer - that would be a huge security concern. But it seems there are some ways to simulate such an effect using iframes. I stumbled upon this jQuery plugin: http://johnculviner.com/jquery-file-download-plugin-for-ajax-like-feature-rich-file-downloads/

 

Demo here: http://jqueryfiledownload.apphb.com/

 

Seems to be pretty neat.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.