Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read from textfile on server using jquery

I have a textfile (.txt) on a server. It contains only one word i.e. ON or OFF. How can i use JQuery or Pure Javascript to read that word from the file.

I am thinking along the lines of $.ajax.

like image 610
prometheuspk Avatar asked Jun 07 '11 17:06

prometheuspk


People also ask

How to read a text file using jQuery?

You can't read a "local" text file with jQuery. jQuery has no access to the client-side filesystem.

How do I read a text file on a server?

A text file on a server can be read with Javascript by downloading the file with Fetch / XHR and parsing the server response as text. Note that the file needs be on the same domain. If the file is on a different domain, then proper CORS response headers must be present.

Can JS read text file?

Yes JS can read local files (see FileReader()) but not automatically: the user has to pass the file or a list of files to the script with an html <input type="file"> . Then with JS it is possible to process (example view) the file or the list of files, some of their properties and the file or files content.

How jQuery read data from JSON file?

The jQuery code uses getJSON() method to fetch the data from the file's location using an AJAX HTTP GET request. It takes two arguments. One is the location of the JSON file and the other is the function containing the JSON data. The each() function is used to iterate through all the objects in the array.


3 Answers

You could use the $.get method to send a GET AJAX request to a resource located on the server:

$.get('/foo.txt', function(result) {
    if (result == 'ON') {
        alert('ON');
    } else if (result == 'OFF') {
        alert('OFF');
    } else {
        alert(result);
    }
});
like image 167
Darin Dimitrov Avatar answered Oct 17 '22 07:10

Darin Dimitrov


You can use $.get to grab the content of that file, and then take action based on the data returned:

$.get('/path/to/file.txt',function(data) {
   if (data == "ON") {

   } else {

   }
});
like image 42
Fosco Avatar answered Oct 17 '22 06:10

Fosco


You can also use this file as a config (for future development) and keep there more informations, for example:

yourfile.txt:

{"enable":"ON","version":"1.0"}

and additionally use JSON to parse file content:

$.get('/path/yourfile.txt', function(data) {
    var config = JSON.parse(data);
    if(config.enable == 'ON') {
         // ...
    } // ...
    if(config.version == '1.0') {
         // ...
    } // ...
});
like image 36
Tomasz Dzięcielewski Avatar answered Oct 17 '22 06:10

Tomasz Dzięcielewski