Andrew Lalis
Andrew Lalis

Reputation: 974

PHP How to update text if a user submits a form

I am trying to make it so a user enters something into a textarea, and once the user submits it, the content will immediately display inside of a div above whose id is "currentMessage". Here is the php file:

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<title>Message Page</title>
		<link rel="stylesheet" href="styles.css" type="text/css"/>
		
		<script type="text/javascript">
			function loadMessage(){
				document.getElementById("currentMessage").innerHTML = "<?php
					$my_file = "msg.txt";
					$handle = fopen($my_file, "r");
					$data = fread($handle, filesize($my_file));
					fclose($handle);
					echo $data;
				?>";
			}
		</script>
		
	</head>

	<body onload="loadMessage();">
		
		<?php include "header.html";?>
		<div>
			<div class="PageTitle">Messaging</div>
			<p class="Paragraph">
				Here you can send a message to the LCD display so that it may be shown when the display
				cycles through its time, temperature and status.
			</p>
			<div class="Paragraph">
				Current Message:<br>
				<p id="currentMessage" class="CodeBlock"></p>
			</div>
			<div class="SubTitle">Enter Your Message:</div>
			<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>" style="clear: left;">
				<textarea cols="32" rows="3" name="msg" maxlength="96" id="msg"></textarea><br>
				<input type="submit" value="Submit Message" name="submit">
			</form>
			<?php
				if (isset($_POST['submit'])){
					$msg = $_POST["msg"];
					$my_file = "msg.txt";
					$handle = fopen($my_file, "w") or die("Cannot open file:  " . $my_file);
					fwrite($handle, $msg);
					fclose($handle);
					echo "<script>
						loadMessage();
					</script>";
				}
			?>
			
		</div>
		
	</body>
	
</html>
Currently, I attempt to save the user's submission to a file on the server, and then run loadMessage() and echo the result in the currentMessage div. However, this obviously isn't working. I'm also new to php and I am not sure how to direct the output of echo, or if there is no way to be more specific as to where to place output text.

Upvotes: 0

Views: 60

Answers (2)

Glubus
Glubus

Reputation: 2855

The problem I think you're having is that you're echo'ing javascript that is not getting evaluated.

Try echoing:

<script>
    (function(){
        loadMessage();
    })();
</script>

instead of just

<script>
    loadMessage();
</script>

pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it

Upvotes: 0

romellem
romellem

Reputation: 6491

So the problem with this is, you are loading the contents of the file before you've saved anything to it. The php code in loadMessage gets executed immediately on page load, and you'd like to execute it after your msg.txt file has been saved.

You can see that this is kind of working if you submit some text once, then try to submit some text again. it'll display what you submitted last time.

Although this overall approach shouldn't be used on an actual website to save info and then load it back to display, if you're just learning there shouldn't be anything wrong with this.

So, to use Javascript to load your data, you need to make an AJAX request.

Typically, most people use jQuery to perform an AJAX request to load data after the page has loaded.

However, to prevent you from including the whole jQuery library, you can use vanilla Javascript to load the msg.txt file asynchronously. This site, http://youmightnotneedjquery.com/#request, has many useful snippets on how to achieve the same effect without the jQuery library.

So, here'd be your code if you loaded the data via Javascript:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Message Page</title>
        <link rel="stylesheet" href="styles.css" type="text/css"/>

        <script type="text/javascript">
            function loadMessage(){
                console.log("Performing AJAX request!");

                var message_element = document.getElementById("currentMessage");
                var request = new XMLHttpRequest();

                // Load our msg.txt file
                request.open('GET', 'msg.txt', true);

                request.onload = function() {
                  if (request.status >= 200 && request.status < 400) {
                    // Success!
                    // Display the text we loaded.
                    resp = request.responseText;
                    message_element.innerHTML = resp;
                  } else {
                    // We reached our target server, but it returned an error
                    message_element.innerHTML = "An error occurred.";
                  }
                };

                request.onerror = function() {
                  // There was a connection error of some sort
                  message_element.innerHTML = "An error occurred.";
                };

                // Send the AJAX request (which displays the data after it has been loaded)
                request.send();
            }
        </script>

    </head>

    <body onload="loadMessage();">

        <?php include "header.html";?>
        <div>
            <div class="PageTitle">Messaging</div>
            <p class="Paragraph">
                Here you can send a message to the LCD display so that it may be shown when the display
                cycles through its time, temperature and status.
            </p>
            <div class="Paragraph">
                Current Message:<br>
                <p id="currentMessage" class="CodeBlock"></p>
            </div>
            <div class="SubTitle">Enter Your Message:</div>
            <form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>" style="clear: left;">
                <textarea cols="32" rows="3" name="msg" maxlength="96" id="msg"></textarea><br>
                <input type="submit" value="Submit Message" name="submit">
            </form>
            <?php
                if (isset($_POST['submit'])){
                    $msg = $_POST["msg"];
                    $my_file = "msg.txt";
                    $handle = fopen($my_file, "w") or die("Cannot open file:  " . $my_file);
                    fwrite($handle, $msg);
                    fclose($handle);
                }
            ?>

        </div>
    </body>
</html>

Upvotes: 1

Related Questions