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
2009-09-10 12:30:13
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
2009-09-10 12:31:21
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
2009-09-10 12:33:33
I don't think a downvote was warranted, the answer is likely to be correct.
AnthonyWJones
2009-09-10 12:34:28
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
2009-09-10 12:35:16
@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
2009-09-10 12:35:43
+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
2009-09-10 12:36:02
@Phoenix: No code server-side is need but the file does need to be visible in website. (+1 BTW to balance things)
AnthonyWJones
2009-09-10 12:37:33
@AnthonyWJones and @Jonathan Sampson, thanks for your response.
rahul
2009-09-10 12:38:34
+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
2009-09-10 12:31:21
Should be noted that the file must reside in the same domain as the request, otherwise a server side proxy will be necessary.
WillyCornbread
2009-09-10 20:18:09
+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
2009-09-10 12:31:51
+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
2009-09-10 12:31:51