简体   繁体   中英

Save Changes to File Without reloading Page

Right now I have an HTML textarea that gets its contents from a text file. What I want to be able to do is allow the user to edit the file in the textarea and when they press a button, the changes get pushed to the file without having to reload the whole page.

I understand this can't be done with javascript alone because its a client side language, but I was thinking this could maybe be done with AJAX somehow? I don't have much experience with AJAX, so that might not work.

I want to stay away from websockets for the sake of simplicity for what I have to do.

Below is my PHP textarea code:

<?php
    $myfile = fopen($file, 'a+');

    echo "<textarea id='demo'>";
    // go through each line in the file, print its contents.
    while(!feof($myfile)) {
          echo fgets($myfile);
    }
          echo "</textarea>";
?>

Well, you have a couple of easy ways of doing it.

  1. you can have a hidden iframe. when the person click on the submit form, you call a function that takes the value of your field send it to a form in your hidden frame, and submit the form using JavaScript.
  2. you can use XMLHttpRequest(); create a php page that takes the data passed to it. call the page using XMLHttpRequest(); sending the data from the form.

method 2 is more elegant.

Without refreshing the whole page you can update the textarea using jquery ajax. When you click save changes on index.php(in my example here), we get the value of the textarea by its id="demo" and send it update.php. In update.php, we use fwrite() to clear all existing text and write the new content we get from our textarea to it, and display the new text like we did in index.php .

So this is index.php :

<!DOCTYPE HTML>
    <html>
        <head>
            <title>TextArea Lesson</title>
             <style>
                 div{
                     margin:0 auto 0;
                     width:400px;
                     height:300px;
                 }
                 #demo{
                     margin-left:5px;
                     width:390px;
                     height:200px;               
                 }
             </style>       
        </head>
        <body>
            <div>
            <form method="POST">
                <fieldset>
                    <legend>Ajax Update Text Area</legend>
        <?php
            $myfile = fopen('test.txt', 'r');
              echo "<textarea id='demo'>";
            // go through each line in the file, print its contents.
            while(!feof($myfile)) {
              echo fgets($myfile);
            }
              echo "</textarea><br>";
        ?>
                    <input type="submit" id="save" value="Save changes" />
                </fieldset>
            </form>
            </div>
        </body>
    </html>
    <script src="https://code.jquery.com/jquery-1.12.2.min.js"
                  integrity="sha256-lZFHibXzMHo3GGeehn1hudTAP3Sc0uKXBXAzHX1sjtk="
                  crossorigin="anonymous"></script>
    <script>
    //when you click save changes, we get its id="save"
    //and prevent default submission    
    $(document).on("click", "#save", function(e){   
            e.preventDefault();
            //get the textarea data bu its id="demo"
            var textdata = $('#demo').val();
            mydata= 'testdata='+textdata;
            $.ajax({
                type:'POST',
                data:mydata,
                url:'update.php',
                success:function(data) {                
                    if(data){
                      alert('Saved!');
                      $("#demo").html(data);//load data from update.php
                    }else{
                      alert('Update failed');
                    }
                  }
            });
        });
    </script>

Update.php :

<?php
$data_to_write = $_POST['testdata'];
$file_path = 'test.txt';
$file_handle = fopen($file_path, 'w'); 
fwrite($file_handle, $data_to_write);
fclose($file_handle);
$myfile = fopen('test.txt', 'r');
 while(!feof($myfile)) {
          echo fgets($myfile);
    }
fclose($myfile);
?>

And test.txt :

The big quick brown black fox jumps over a lazy dog.

I hope this may help you. Note: This is just a working code and for learning purpose only. So security checking and data validation is not ensured.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM