para club101 para club101 - 5 months ago 17
HTML Question

how to transfer data from one html page to another using javascript

I'm trying to transfer data from one html page to another page, so I wrote this program:

page1.ejs:

<a href="/events" onclick="send()">
<span class="message">
new alert
</span>
</a>

function send() {
$mesg = $('.message');
var msg = $mesg.text();
var msg1 = msg.replace(/\s/g, '');
localStorage.setItem("message", msg1);
}


page2.ejs:

<script src="socket.io/socket.io.js"></script>
<script>
document.getElementById("event").innerHTML = localStorage.getItem("message");
</script>
<td id="event"></td>


But I don't get the data transferred from the pages? what is my mistake?

Answer

The issue is in page2.ejs:

Problem: The HTMLElement <td id="event"></td> is not yet available when your <script> block is parsed and executed, so document.getElementById("event") returns undefined.

Solution: Move the <script> block to the bottom, beneath <td id="event"></td> and it should work.