Skip to content
Advertisement

Headers downloading actual page content, not the csv file I’ve constructed

My goal here is to have the browser download a csv file using headers to do it. For some reason yet to be determined, the browser seems to be downloading the HTML content of the current page (and not the contents of the array I’ve given it).

Here is the code I’ve been using:

JavaScript

I’ve followed the instructions of many articles / SO questions I’ve read and I don’t see what’s wrong with this code.

I of course appreciate any help that I can get here!

Here is the complete code (upon request):

JavaScript

Advertisement

Answer

Try this code:

JavaScript

I have looped the data to build the CSV as your code would not produce the result you expect. I have also retrieved the file as a string before outputting – this is just a nicety to add a Content-Length header. I have also – and this is the important bit – called exit to output the data, to prevent any more code being executed any prevent and HTML after this code being output.

If you are using this code and still having a problem, then the code is not being called – you should check any if statements etc that this code is wrapped in.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement