views:

265

answers:

5

How do I read contents from a server side file using javascript?

+2  A: 

This is not possible using plain javascript. Javascript runs in the client browser and you cannot access a file in server. You can use AJAX to do this.

rahul
Sure it, is assuming the Javascript is running on the server, which it probably isn't but the question doesn't make that clear as yet
AnthonyWJones
This can be done with plain javascript, no additional frameworks required:var xmlhttp;if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); }else if (window.ActiveXObject) { // code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }else { alert("Your browser does not support XMLHTTP!"); }xmlhttp.onreadystatechange=function(){if(xmlhttp.readyState==4) { document.myForm.time.value=xmlhttp.responseText; }}xmlhttp.open("GET","time.asp",true);xmlhttp.send(null);
Nerdling
I don't think a downvote was warranted, the answer is likely to be correct.
AnthonyWJones
But you have to code from server side to process the AJAX request. Thats why I made the comment that it is not possible using plain javascript. Also I mentioned about AJAX in my answer.
rahul
@Nerdling: that would the AJAX then that phoenix was refering to right? It would have been better for you to place this code in an answer than to place that unformatted mess in the comments.
AnthonyWJones
+1 Javascript can read the output of a file, but not the contents. @Nerdling, your example is reading the output, not the contents. You will not be able to see the ASP itself with your method.
Jonathan Sampson
@Phoenix: No code server-side is need but the file does need to be visible in website. (+1 BTW to balance things)
AnthonyWJones
@AnthonyWJones and @Jonathan Sampson, thanks for your response.
rahul
+2  A: 

using Ajax (XmlHttpRequest) e.g. using jQuery:

jQuery.get( url, [data], [callback], [type] )

veggerby
+10  A: 

Ask the web server for it with Ajax. In jQuery speak, for instance:

jQuery.get('path/to/file/on/server.txt', null, function(data, status) {
    // your file contents are in 'data'
});
Warren Young
Should be noted that the file must reside in the same domain as the request, otherwise a server side proxy will be necessary.
WillyCornbread
+1  A: 

The quick answer is "you can't".

If you make the server side file accessible through your web server, you can use an xmlhttprequest, a.k.a ajax, to retrieve it.

Justin Dearing
+2  A: 

You have to serve the file via a HTTP request (i.e., the file is available as a URL like www.conphloso.com/somefile.txt), which you can grab via an ajax request in the background.

Will