0

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.
Andrew Lalis
  • 597
  • 3
  • 11
  • 23
  • Are you getting any errors? Can you use var_dump($_POST) at the start of your php script? Also you don't really need to write your users post message data to a file if all you want is to put it in a div temporarily. You can just directly put $_POST['msg'] into your html element. If you do in fact want to store it you should use a database. (though I get that you're just writing it to file for now) – Glubus Dec 23 '15 at 15:07
  • Here's what I got from var_dump($_POST): array(2) { ["msg"]=> string(16) "Testing Message." ["submit"]=> string(14) "Submit Message" } Also, it does not throw any errors in the console. – Andrew Lalis Dec 23 '15 at 15:11
  • why won't you simply use javascript for that? PHP is not needed, neither any additional save files – Flash Thunder Dec 23 '15 at 15:49
  • The point is that this will be on a webserver, and the text will be saved so it can be accessed by a python program that interprets it. – Andrew Lalis Dec 23 '15 at 15:54

2 Answers2

1

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>
romellem
  • 3,144
  • 1
  • 22
  • 50
  • should it not be `onclick` rather than `onload`. I'm thinking it should load the html first with the text area and then when the user clicks submit there should be a handler `onclick` or `on('click')` – learningbyexample Dec 23 '15 at 15:37
  • This function works, but only on the initial page loading, and submitting the form does not trigger the function, so I added `echo "";` However, it still only loads once. – Andrew Lalis Dec 23 '15 at 15:45
  • True, the bad thing about this code is if msg.txt doesn't exist, on first page load, you'll get the "error" text. However, since they are POSTing their data, having an `onclick` handler wouldn't really matter. The page refreshes after the POST submit, so the js click handler probably won't get executed. Even if it does, it'll only display for a very short amount of time. – romellem Dec 23 '15 at 15:47
0

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

Community
  • 1
  • 1
Glubus
  • 2,704
  • 1
  • 9
  • 24