-4

I just want to create a button that when I click on it, it will read a text file I have in the same directory as this php file. I create this code but when I click at ethe button nothing happens.. Did I make something wrong? Can someone help me because I a beginner at php and javascript. Thanks,

<!DOCTYPE html>
<html>
<body>



<button onclick="read()">Click me</button>

<p id="demo"></p>

<script>
function read(){
  
$myfile = fopen("lala.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("lala.txt"));
fclose($myfile);

}
</script>

</body>
</html>
tararam
  • 21
  • 5

2 Answers2

0

If you want to read using click in javascript, you can use AJAX like this

index.html

<html>
<title>Your Page</title>
<script>
function load()
{
    var xmlHttpRequest;
    if (window.XMLHttpRequest)
    {
        xmlHttpRequest = new XMLHttpRequest();
    }
    else
    {
        xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");            
    }

    xmlHttpRequest.onreadystatechange=function()
    {
        if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200){
            document.getElementById("ajaxInfo").innerHTML = xmlHttpRequest.responseText;
        }
    }

    xmlHttpRequest.open("GET", "ajax_file.txt",true);
    xmlHttpRequest.send();
}

</script>
</head>
<body>
<div id="ajaxInfo"> </div>
<button type="button" onclick="load()">Go!</button>
</body> 
</html>

and some text file like ajax_file.txt

Your file to read here, everything
Aaron Magpantay
  • 405
  • 1
  • 5
  • 17
  • Ok. Reallu helpful. And if I want to check for an attribute inside this file if it is true or false how do I do that?F.ex inside the file I read exists an attribute x. I want to check if it is true or false. – tararam Mar 18 '17 at 15:36
  • better way to achieve what you want is parse it first in another php file before getting it to load to you own page so you don't have to check any... What are you planning on making? – Aaron Magpantay Mar 18 '17 at 15:45
0

JavaScript and PHP are two different things.

As far as my JavaScript knowledge goes, you can't read files directly from your file system with standard JavaScript. If you're using NodeJS, then you can because it extends standard JS.
The only way of reading a file in JS is to make a GET request to the file:

var xhr = new XMLHttpRequest();
xhr.open("GET", "relative/path/to/file.txt", false);
xhr.send()
console.log(xhr.responseText);

This will request the file on your server synchronously (blocking request) and log its contents to the JavaScript console.

Community
  • 1
  • 1
guilherme.oc97
  • 431
  • 1
  • 3
  • 13