Go Back   CodingForums.com > :: Client side development > JavaScript programming > Post a JavaScript

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rating: Thread Rating: 4 votes, 5.00 average.
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 07-03-2008, 10:10 PM   PM User | #1
rnd me
Senior Coder

 
rnd me's Avatar
 
Join Date: Jun 2007
Location: Urbana
Posts: 3,462
Thanks: 9
Thanked 466 Times in 450 Posts
rnd me is a jewel in the roughrnd me is a jewel in the roughrnd me is a jewel in the rough
Loading and Saving Files

Loading and Saving Files with browser javascript

Most of the ajax examples I've come across are complicated and use a two-step asynchronous process to fetch data.
new users get lost in the status checking and callback writing, and simply want to load a text file like a csv log file, an m3u playlist, or a css stylesheet into a variable.

browser javascript can use standard http methods like
GET, PUT, and DELETE to create, modify, and manage files on a remote server.


Setup:


for reading:
no setup is required to simply read a file into a string. while i have found way to sniff out ajax-type requests like used below, i haven't noticed anyone doing so.


for writing
The only configuration needed on the server, is the allowance of public or user-based write permissions. check configuration section of your hosting providers. most allow you to setup public read-private write on files. that's great because everyone can instantly see the changes only you can make.
browsers should automatically ask you to login if you try to write to a file that has private write. Assigning the permissions to the urls you will use in this code is a critical security consideration.

setup can be done with winxp pro's iis server by right-clicking a folder in the IIS web site folder-view. (run compmgmt.msc to view)

if you use apache, then you will need a bit of server-side code called a
put handler
to catch the PUT requests. (module here)

however, many apache installations have these capabilities ready to go.



the IO function:

Code:
function IO(U, V) {//LA MOD String Version. A tiny ajax library.  by, DanDavis
    var X = !window.XMLHttpRequest ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest();
    X.open(V ? 'PUT' : 'GET', U, false );
    X.setRequestHeader('Content-Type', 'text/html')
    X.send(V ? V : '');
return X.responseText;}
arguments[0] is the url (relative or absolute) of the file you want to access.
arguments[1] is an optional string .
if arguments[1] is set to anything, IO places that string into the url passed in arguments[0]




A tested cut-and-paste example:
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>javascript-only file writing</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<h1>javascript fileIO demo</h1>	
open <a href='newPage.htm' target="_blank">my new page</a> in a new tab/window.
<br />
<br />

<textarea rows='10' cols='80' id='userValue'>Hello World</textarea>	
<br />

<input type='button' value='Save' onclick="doSave()"  />	

&nbsp;&nbsp;&nbsp;
<input type='button'  value='Load' onclick="doLoad()"  />	

<script type='text/javascript'>


function el(tid) {return document.getElementById(tid);}

function IO(U, V) {//LA MOD String Version. A tiny ajax library.  by, DanDavis
    var X = !window.XMLHttpRequest ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest();
    X.open(V ? 'PUT' : 'GET', U, false );
    X.setRequestHeader('Content-Type', 'text/html')
    X.send(V ? V : '');
return X.responseText;}	


function doSave(){
	IO("newPage.htm" , el("userValue").value ); 
}

function doLoad(){
	el("userValue").value = IO("newPage.htm"); 
}

</script>


</body>
</html>

So will this work for me?

working servers support GET, so consider IO's read capability reliable.

you can check what methods your server supports by saving the code below as "servertest.htm" (or whatever) and opening it your browser.
it will list the HTTP verbs your server will support. for saving files, you need PUT.



Code:
<html><head><script>

    function sOptions(tUrl) { //server options
        var XHRt =  !window.XMLHttpRequest ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest();
        XHRt.open("OPTIONS", tUrl , false);
        XHRt.send("");
        return XHRt.getResponseHeader("Allow").split(/\W+/g);
    }

  document.write (sOptions(window.location.href));
  document.close()
</script></head</html>


One more bonus (no example)
if you are allowed to do so, you can delete files as well:


Code:
function DELETE(U) {//LA MOD  A tiny ajax library.  (c)2007, DanDavis
    var X = !window.XMLHttpRequest ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest();
    X.open("DELETE");
    X.send('');
return X.status;}
__________________
my site (updated 5/13)
STATS (2013/5) HTML5:90.2% MOB:14% IE7:0.5% IE8:8.6% IE9:9.8% IE10:10%

Last edited by rnd me; 07-03-2008 at 10:17 PM..
rnd me is offline   Reply With Quote
Old 12-02-2010, 02:55 PM   PM User | #2
silverwatersask
New to the CF scene

 
Join Date: Dec 2010
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
silverwatersask is an unknown quantity at this point
Reading from file

Realizing this is an old thread.

I have a couple of questions and thought best to have the answers included here.

First the script works fine....except that it always gets OLD data from the cache and not from the file....how can I fix this problem.

Second --- if I use window.setInterval with this will it keep bringing in the new values (after concern 1 is answered).

thanks

Brian
silverwatersask is offline   Reply With Quote
Old 12-10-2010, 03:41 AM   PM User | #3
rnd me
Senior Coder

 
rnd me's Avatar
 
Join Date: Jun 2007
Location: Urbana
Posts: 3,462
Thanks: 9
Thanked 466 Times in 450 Posts
rnd me is a jewel in the roughrnd me is a jewel in the roughrnd me is a jewel in the rough
Quote:
Originally Posted by silverwatersask View Post
Realizing this is an old thread.

I have a couple of questions and thought best to have the answers included here.

First the script works fine....except that it always gets OLD data from the cache and not from the file....how can I fix this problem.
ajax uses regular http caching stratgies, just like the browser.

you can alter your server config, telling it not to cache the files in question.

there might be a head that will force an update, but an incorrectly configured server can foil the best plans.

the one sure way to get a fresh copy is to ask for a different url each time. you can get the same file at different urls using the "queryString" (aka location.serach) and adding something unique. the simplest, if you won't request more than one per second is url+Date().

it's traditional to use the date serial or Math.random().

ex:
Code:
function doLoad(){
	el("userValue").value = IO("newPage.htm" + "?" + (new Date).getTime() ); 
}
__________________
my site (updated 5/13)
STATS (2013/5) HTML5:90.2% MOB:14% IE7:0.5% IE8:8.6% IE9:9.8% IE10:10%
rnd me is offline   Reply With Quote
Old 02-06-2011, 12:04 PM   PM User | #4
hubertdennis
New to the CF scene

 
Join Date: Feb 2011
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
hubertdennis is an unknown quantity at this point
Hello everybody ,

can u help me ?Ihave a problem,how can i upload a text file using AJAX httprequest ? it is to do that with this"tested cut-and-paste example" ? when yes , how can i do that ?please show me , i want to resolve this Problem.I have try this example but it not work.should i configure anything before it works?I will very happy to your response.

excuse me for me English it's very poor..

Thank you in Advance

Denis
hubertdennis is offline   Reply With Quote
Old 02-07-2011, 07:18 AM   PM User | #5
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,037
Thanks: 197
Thanked 2,411 Times in 2,389 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
See:- http://www.codingforums.com/showthread.php?t=17515.

You will not get any reply in this forum which is intended to be used only to
post a completed (working) script for showcasing/benefit of others.


Post this question in the Ajax and Design Forum.
Philip M is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 06:36 AM.


Advertisement
Log in to turn off these ads.