Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 963
ramesh kumar Avatar asked Oct 24 '25 18:10

ramesh kumar


2 Answers

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');
like image 189
Michael Seibt Avatar answered Oct 26 '25 09:10

Michael Seibt


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>
like image 23
jamietelin Avatar answered Oct 26 '25 09:10

jamietelin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!