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.

4
  • what do you mean by 'locally'? Commented Jul 17, 2013 at 16:11
  • possible duplicate of create a file using javascript in chrome on client side Commented Jul 17, 2013 at 16:12
  • like a window pop-up opens letting the user save the output as myFile.xml on their local hdd. Commented Jul 17, 2013 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. Commented Jul 17, 2013 at 16:17

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.