1

I'm making an AJAX request to the server and getting a response as XML text and I've tried a bunch of ways to transform it into a downloadable file but none are working.

I've done something similar for a pdf but the difference is that for the pdf the content is returned as a blob, here's the code:

         $.ajax({
            method: "GET",
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", bearer));
            },
            url: url,
            xhrFields: {
                responseType: "blob"
            },
            success(blob) {
                var link = document.createElement("a");
                link.href = window.URL.createObjectURL(blob);
                link.download = "file.xml";
                link.click();
            }
        });

How can I transform this code so it works the same way when receiving XML text?

7
  • 2
    request.setRequestHeader("Content-Type", "application/pdf"); makes no sense. You are making a GET request. The body has no content to describe the type of. Commented Feb 19, 2020 at 10:55
  • 2
    "How can I transform this code so it works the same way when receiving XML text?" — Do nothing. (Well, you might want to change file.pdf to file.xml). It should just work. What's the problem? Commented Feb 19, 2020 at 10:56
  • 1
    Why creating a link element? If you have an url it mimicks the same as you change the url of the current page. (Like location.href) Commented Feb 19, 2020 at 11:00
  • 1
    @VítorMartins what I mean is if you create a link on the fly and click it programatically, it's the same as a redirect. If you want a file to be downloaded and not opened within the browser, you can use Content-Type: application/octet-stream and Content-Disposition: attachment; filename="file.xml". It works if you receiving the url of the xml and not the content of the xml. Commented Feb 19, 2020 at 12:06
  • 1
    @VítorMartins glad to hear! Commented Feb 19, 2020 at 13:41

1 Answer 1

1

If you receive the url of the XML and not the content of the XML file, you can use the headers like

Content-Type: application/octet-stream
Content-Disposition: attachment; filename="file.xml"

It forces the browser to download the XML. You don't need to create a link on the fly and click it programatically, just open the received url by redirecting (location.href) or open in new window/tab (window.open). Latter is handy if you want to make sure to stay on the current page but restricted in some cases. Have fun!

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

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.