I'm trying to get client-side javascript objects saved as a file locally. I'm not sure if this is possible.
The basic architecture is this:
Ping an external API to get back a JSON object
Work client-side with that object, and eventually have a "download me" link
This link sends the data to my server, which processes it and sends it back with a mime type application/json, which (should) prompt the user to download the file locally.
Right now here are my pieces:
Server Side Code
<?php
$data = array('zero', 'one', 'two', 'testing the encoding');
$json = json_encode($data);
//$json = json_encode($_GET['']); //eventually I'll encode their data, but I'm testing
header("Content-type: application/json");
header('Content-Disposition: attachment; filename="backup.json"');
echo $_GET['callback'] . ' (' . $json . ');';
?>
Relevant Client Side Code
$("#download").click(function(){
var json = JSON.stringify(collection); //serializes their object
$.ajax({
type: "GET",
url: "http://www.myURL.com/api.php?callback=?", //this is the above script
dataType: "jsonp",
contentType: 'jsonp',
data: json,
success: function(data){
console.log( "Data Received: " + data[3] );
}
});
return false;
});
Right now when I visit the api.php site with Firefox, it prompts a download of download.json and that results in this text file, as expected:
(["zero","one","two","testing the encoding"]);
And when I click #download to run the AJAX call, it logs in Firebug
Data Received: testing the encoding
which is almost what I'd expect. I'm receiving the JSON string and serializing it, which is great. I'm missing two things:
The Actual Questions
What do I need to do to get the same prompt-to-download behavior that I get when I visit the page in a browser
(much simpler) How do I access, server-side, the json object being sent to the server to serialize it? I don't know what index it is in the GET array (silly, I know, but I've tried almost everything)