Skip to content
Advertisement

How to save current state of html body php

I have a html website with Sortable.js. I want to save the current state of the body when a user rearranges the list and clicks a save button. I don’t want it to save to local storage but directly to the hosted file, replacing the body html with the new rearranged version.

<body>
  <div class='wrapper'>
    <ul class='list'>
      <li class='item' contenteditable='true'>Item 1</li>
      <li class='item' contenteditable='true'>Item 2</li>
      <li class='item' contenteditable='true'>Item 3</li>
    </ul>
    <button class='add-item'>add new item</button>
    <button class='save'>save changes</button>
  </div>
</body>

I believe what I’m trying to achieve is very simple and can be done using php and ajax, but I can’t find any direct answer to my question.

Currently there is only one index.php file.

Security is no issue.

Advertisement

Answer

You can to something like this…

   <body>
      <div class='wrapper'>
        <ul class='list'>
          <li class='item' contenteditable='true'>Item 1</li>
          <li class='item' contenteditable='true'>Item 2</li>
          <li class='item' contenteditable='true'>Item 3</li>
        </ul>
        <button class='add-item'>add new item</button>
        <button class='save' onclick="saveHTML()">save changes</button>
      </div>
    </body>

Java script

function saveHTML(){
  var currentStateHTML = document.documentElement.innerHTML;
  console.log(currentStateHTML);//For debugging
  $.post("file.php", {type : "save", state : currentStateHTML},
     function(data, status){
        if(status == "success"){
          if(data == "saved"){
            location.reload();//which is index.php itself
          }
          else console.log("error");
        }
     }
  );
}

php file

<?php
  if(isset($_POST['type'])){
     if($_POST['type'] == "save"){
        $html = $_POST['state'];
        if(file_put_contents("index.php", $html)){
           echo "saved";
           //The file got updated
        } 
        else "error";
     }
  }
?>

Note:- Updating/Erasing/Appending to a file in your case html/php file is a complex and sensitive task, you can explore more on this, the above code is just an example and might be inappropriate.

Suggestions:-

  1. Do not try to update file containing php script, why.? because document.documentElement.innerHTML; will only get you the frontend of your page, which is risky while updating the actual backend file.
  2. Save all/updatable/editable file {containing only front end view} in a separate folder, and do changes accordingly, and when saved/changed/reloaded include these files into your page.
  3. Try to keep the front end and back end scripts as separately as possible.

For any queries comment down.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement