13

Does anyone know of a tutorial on how to read data from a server side file with JS? I cant seem to find any topics on this when I google it. I tried to use but it does not seem to work. I just want to read some data from a file to display on the page. Is this even possible?

var CSVfile = new File("test.csv");
var result = CVSfile.open("r");
var test = result.readln();
shinjuo
  • 20,498
  • 23
  • 73
  • 104
  • 1
    Are you running the JS in a web page? If so what do you mean by reading "server side file", the java script code gets executed on the client side (browser) and the way to get files from the server is making an http request. – Jaime Aug 25 '10 at 15:14
  • 2
    the file I have is stored on the server and the script will run on page load. Is it even possible to do this? – shinjuo Aug 25 '10 at 15:15
  • 1
    As others mention, search for AJAX, and use jQuery or MooTools (or other framework) to ease your way into doing this. – Jaime Aug 25 '10 at 15:17
  • 1
    Check out my answer - I've updated it with a small example using the Mootools library. – Seidr Aug 25 '10 at 15:24
  • Awesome I will look into figuring this out – shinjuo Aug 25 '10 at 15:51
  • After looking at AJAX I saw that someone suggested using PHP. Can I use PHP to read a file on the web? – shinjuo Aug 25 '10 at 16:37
  • Yes, you can use PHP to read files. PHP is a server-side technology that will render HTML results to the calling client when processing completes (which can include scripts). There are dozens of books and web sites on PHP, just look up read file. (It's very similar conceptually to working with a database). The caveat is your hosting server needs PHP installed in order to use it. – Tim Dec 30 '15 at 20:14

2 Answers2

9

To achieve this, you would have to retrieve the file from the server using a method called AJAX.

I'd look into JavaScript libraries such as Mootools and jQuery. They make AJAX very simple use.

<html>
    <head>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/mootools/1.6.0/mootools-core.min.js"></script>
        <script type="text/javascript">
            //This event is called when the DOM is fully loaded
            window.addEvent("domready",function(){
                //Creating a new AJAX request that will request 'test.csv' from the current directory
                var csvRequest = new Request({
                    url:"test.csv",
                    onSuccess:function(response){
                        //The response text is available in the 'response' variable
                        //Set the value of the textarea with the id 'csvResponse' to the response
                        $("csvResponse").value = response;
                    }
                }).send(); //Don't forget to send our request!
            });
        </script>
    </head>
    <body>
        <textarea rows="5" cols="25" id="csvResponse"></textarea>
    </body>
</html>

If you upload that to the directory that test.csv resides in on your webserver and load the page, you should see the contents of test.csv appear in the textarea defined.

GOXR3PLUS
  • 6,877
  • 9
  • 44
  • 93
Seidr
  • 4,946
  • 3
  • 27
  • 39
  • Consider using a newer version of mototools cause that one has very bad conflicts with JQuery you can use -> – GOXR3PLUS Jul 27 '17 at 08:11
7

You need to use AJAX. With jQuery library the code can look like this:

$.ajax({ url: "test.csv", success: function(file_content) {
    console.log(file_content);
  }
});

or if you don't want to use libraries use raw XMLHTTPRequest object (but you I has different names on different browsers

function xhr(){
  var xmlHttp;
  try{
    xmlHttp=new XMLHttpRequest(); 
  } catch(e) {
    try {
      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); 
    } catch(e) {
      try {
        xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); 
      } catch(e) {
        alert("Your browser does not support AJAX!"); 
        return false;
      }
    }
  }
  return xmlHttp; 
}
req = xhr();
req.open("GET", "test.cvs");
req.onreadystatechange = function() {
  console.log(req.responseText);
};
req.send(null);

UPDATE 2017 there is new fetch api, you can use it like this:

fetch('test.csv').then(function(response) {
    if (response.status !== 200) {
        throw response.status;
    }
    return response.text();
}).then(function(file_content) {
    console.log(file_content);
}).catch(function(status) {
    console.log('Error ' + status);
});

the support is pretty good if you need to support browser that don't support fetch API you can use polyfill that github created

jcubic
  • 61,973
  • 54
  • 229
  • 402