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.
CodePudding user response:
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:-
- Do not try to update file containing
php
script, why.? becausedocument.documentElement.innerHTML;
will only get you thefrontend
of your page, which is risky while updating the actual backend file. - 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.
- Try to keep the front end and back end scripts as separately as possible.
For any queries comment down.