ramesh kumar
ramesh kumar

Reputation: 1707

Javascript - reading a file (not uploaded file,but file present in the same directory as the html file)

i tried a lot for this, but didnt find the answer . How can i read a file using javascript or html . I have a text file "sample.txt" and i have some information in it . It is placed in the same folder as the html file is placed where the html file contains the html code that deals with this file . I just want to read the information from the file and display it on some div or whatever, i mainly want to know how to read a file .

Will provide more information if necessary .

Thanks

Upvotes: 4

Views: 1642

Answers (3)

lejahmie
lejahmie

Reputation: 18253

You can do a regular Ajax request without jQuery aswell to read a file.

Following uses a GET request to get data from myfile.txt and outputs it to the DIV-tag with id output.

<script>
function ajaxGet()
{
var xmlhttp;
if (window.XMLHttpRequest)
  {
  xmlhttp=new XMLHttpRequest();
  }
else
  {
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("output").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","myfile.txt",true);
xmlhttp.send();
}
ajaxGet();
</script>

<div id="output"></div>

Upvotes: 1

Michael Seibt
Michael Seibt

Reputation: 1346

At first: JavaScript is executed on client-side. Though you have to put up an AJAX-Request to fetch the content of your file. I think jQuery's load() seems to be the easiest way to achieve this.

For example:

$('#theContentElement').load('sample.txt');

Upvotes: 3

henryabra
henryabra

Reputation: 1443

You may fetch the actual file content using javascript. Here is a sample code using jquery using the load function:

$("#YOUR_DIV_ID").load("sample.txt");

This will update the content of the div with the id YOUR_DIV_ID with the content of "sample.txt"

Upvotes: 0

Related Questions