Save as CSV using javascript

Discussion in 'JavaScript' started by sherekhan2, Sep 25, 2008.

  1. #1
    I've a very simple html+javascript page using the document.getElementByID().innerHTML to write a specific div.

    I'd like to add a button or a link to save this div directly as CSV on the client side without having to write a file or into the DB on the server.

    How can I achieve this in javascript?

    <html> 
     <head>
    
    	<script type='text/javascript'>
    	
    		function MyFunction() {
    			
    			if certain condition is true
    								
    					document.getElementById('SectionDiv').innerHTML=
    					someHTMLcode+document.getElementById('SectionDiv').innerHTML;
    								
    			else do nothing					
    		
    		}
    	
    	
    	</script>
    
    
    	<style type='text/css'>
    	
    		SomeCSS
    		
    	</style>
    
    	<!--[if IE]>
    		<style>
    		
    		SomeSpecificIE_CSS
    		
    		</style>
    	<![endif]-->	
    
    </head>
    
    <body>
      
    
    	<div id='main'>
    		<button type='button' onclick='MyFunction()'>ButtonText</button>		
    	</div>
    
    
    	<div id='SectionDiv'>	
    		MyFunction is writing into this Div
    	</div>
    
    
    </body>
    </html>
    Code (markup):

     
    sherekhan2, Sep 25, 2008 IP
  2. joebert

    joebert Well-Known Member

    Messages:
    2,150
    Likes Received:
    88
    Best Answers:
    0
    Trophy Points:
    145
    #2
    Not possible, I've wanted to do something similar for years.
     
    joebert, Sep 27, 2008 IP
  3. dimitar christoff

    dimitar christoff Active Member

    Messages:
    882
    Likes Received:
    62
    Best Answers:
    0
    Trophy Points:
    90
    #3
    why wouldn't it be possible? i don't see any problem coding this.
     
    dimitar christoff, Sep 28, 2008 IP
  4. joebert

    joebert Well-Known Member

    Messages:
    2,150
    Likes Received:
    88
    Best Answers:
    0
    Trophy Points:
    145
    #4
    Because Javascript doesn't have a method for generating an actual file or an HTTP header that would prompt the browser to download javascript content in place of a file.
    You have to go to the server.

    Coding everything up until that point is simple.

    If it was possible, I would have written an .htaccess file generator for Windows users that didn't need to go to the server to generate the file by now. :)
     
    joebert, Sep 28, 2008 IP