3

I'm making an AJAX request. The returned response is a XML.

How can I let the user save the response as a XML file locally on success ?

$.ajax({
    type: "POST",
    url: url,
    data: JSON.stringify(myJson),
    contentType: "application/json",
    dataType: format,
    success: function(response)
    {
        console.log("Exported JSON: " + JSON.stringify(myJson));
        console.log(response);
        jQuery.parseXML(response);
    },
    error: function()
    {
        console.log(arguments);
        alert("Export process failed.");
    }
});

The format in this case is xml.

Mythul
  • 1,807
  • 7
  • 34
  • 53
  • what do you mean by 'locally'? – user1 Jul 17 '13 at 16:11
  • possible duplicate of [create a file using javascript in chrome on client side](http://stackoverflow.com/questions/7160720/create-a-file-using-javascript-in-chrome-on-client-side) – Quentin Jul 17 '13 at 16:12
  • like a window pop-up opens letting the user save the output as myFile.xml on their local hdd. – Mythul Jul 17 '13 at 16:12
  • since you are not creating the xml file dynamically, I would rather use a `link` to that page and maybe open it in a new tab. – user1 Jul 17 '13 at 16:17

2 Answers2

2

Using a data URI will get you part way there.

window.open("data:text/xml;base64," + window.btoa(xmlString));

Using "application/octet-stream" instead of "text/xml" will even force a download prompt in FF and Chrome.

Unfortunately data URIs have size limits and there's probably a more clever approach using content editable and the exec 'save' or 'saveas' command.

Louis Ricci
  • 20,804
  • 5
  • 48
  • 62
1

On success, render the response XML in a textarea or just a div and have the user copy+paste the results into a text editor. They can then save the file from the editor.

or

Instead of emitting the xml directly, provide a link to it instead.

SonOfSofaman
  • 21
  • 1
  • 3