0

I have JSON array in the client side which is rendered in UI. User want to download the contents as file. How can i send a content from client side to server and download as a file.

I found that POST Ajax request will not allow us to download a file. How can i do it?

Fizer Khan
  • 88,237
  • 28
  • 143
  • 153
  • Related: http://stackoverflow.com/questions/566922/how-do-i-download-javascript-string-as-a-file?rq=1 – Marc B Jun 04 '13 at 17:00
  • Is the JASON accessible from the server as a separate file? Does it have a URL? – HBP Jun 04 '13 at 17:02
  • Do you *really* want to download a file using JavaScript, or would you be satisfied simply coercing the browser to do a download of the resource instead of displaying it when the browser navigates to the resource? – apsillers Jun 04 '13 at 17:03
  • apsillers: I want to display the reports which involves some complex operation in the server side. Once server finishes the Job, it sends an JOSN array to the client. Client shows the JSON data in some tabular format. Users also want to download same data in CSV and PDF format. Here i dont want to perform the complex operation again to download the data. So i decided to send same JSON array from client to server and download as CSV or PDF format. – Fizer Khan Jun 05 '13 at 10:27

1 Answers1

1

If the content is only available in the client, you'll have to send it to the server. Try something like this:

<a id="download_link">Download</a>
$('#download_link').on('click', function(e){
    e.preventDefault();
    window.location = 'my-handler.php?json=' + myJsonString;
});
// or without jQuery
document.getElementById('download_link').onclick = function(){
   window.location = 'my-handler.php?json=' + myJsonString;
};

Then force the download in my-handler.php, using the data sent to the server as the file content:

// Use equivalent in your server side script if not using PHP
$filename = 'download-'.time().'.json';
header('Content-Type: application/octet-stream');
header('Content-Transfer-Encoding: Binary');
header('Content-disposition: attachment; filename="'.$filename.'"'); 
exit($_GET['json']);

Using this method, the current window should not be replaced but the download prompt should start, but you can open in a new window if you like.

This is a quick and dirty solution. Note that this will allow a person to type in anything and download a file. It might be wise to at least validate the content first. There may also be issues with the content being too large.

Wesley Murch
  • 101,186
  • 37
  • 194
  • 228
  • Although it should work, I feel like this may be a bad solution, but I can't quite imagine a good alternative without getting too complicated. Looking forward to comments. – Wesley Murch Jun 04 '13 at 17:26