'How do I read from a file in PHP and complete the action in JavaScript/CSS?

Let's say I have 2 boxes and a text file called data.txt:

<?php 
    $myfile = fopen("data.txt") or die("Unable to open file");
 ?>
<button> Go </button>
<div id = "box1" >
    <h5> BOX 1 </h5>
<?php echo fread($myfile,filesize("data.txt")); ?>
</div>

<div id = "box2>
<h5> BOX 2 </h5>
</div>
#box1 {
      width: 100px;
      height: 200px;
      background-color: red;
      position: absolute;
      left: 0px;
      top: 0px;
      text-align: center;
      font-family: Times New Roman;
    }

#box2 {
      width: 100px;
      height: 200px;
      background-color: white;
      position: absolute;
      left: 0px;
      top: 0px;
      text-align: center;
      font-family: Times New Roman;
    }

How do I move the text from the text file, "Hello World" from box 1 to box 2 using plain JavaScript?



Solution 1:[1]

I assume you want to move the text from box1 to box2 when the user clicks the button. I have substituted some hard coded text in place of the contents of the file. Also I have used spans and added some id attributes to make it easier to access the elements using JavaScript. I think the snippet below does what you want as clicking on the Go button moves the text from box1 into box2:

const span1Id = document.querySelector('#span1-id');
const span2Id = document.querySelector('#span2-id');
const goBtn = document.querySelector('#go-btn');
goBtn.addEventListener('click', function(){
  span2Id.innerText = span1Id.innerText;
});
<button id="go-btn"> Go </button>
<div id="box1" >
    <h5> BOX 1 </h5>
    <span id="span1-id">Text from file</span>
</div>

<div id="box2">
    <h5> BOX 2 </h5>
    <span id="span2-id"></span>
</div>

You may need the div elements for other reasons but they are not used in my example. The following HTML would work exactly the same:

<button id="go-btn"> Go </button>

<h5> BOX 1 </h5>
<span id="span1-id">Text from file</span>

<h5> BOX 2 </h5>
<span id="span2-id"></span>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1