is it possible to get data that contain html element from content editable div.
<div id="content" name="content" contenteditable="true" spellcheck="false"\>
<b>hallo</b>world
CodePudding user response:
There are many ways to do that but one of the best way you can start is by learning these things :
- DOM
- JavaScript
- Sending HTTP request
- Getting Data from HTTP request with PHP
- Save the data in DB with PHP
CodePudding user response:
You can use the example below, Press Button Save, It will alert the data stored in div.
<!DOCTYPE html>
<html>
<body>
<div id="content" name="content" contenteditable="true" spellcheck="false"\>
<b>hallo</b>world
</div>
<button onClick="textFromDiv()">Save</button>
</body>
<script>
function textFromDiv(){
var divText = document.getElementById('content'),
htmlContent = divText.innerHTML;
alert(htmlContent);
}
</script>
</html>
After this you can use the variable htmlContent that contains the data inside the div.
CodePudding user response:
In order to insert
the text/html content from a contendeditable
element within a webpage you will need to use Javascript to either send via ajax ( as suggested earlier ) or send as a regular form submission to the server.
In the following code example the actual content is sent using fetch
to the server - in this case it simply uses location.href
to point to itself but in practice this could be a normal script path, such as /path/to/script.php
On the server, the PHP script will have access to the POST
array and specifically content
via $_POST['content']
- from which point you can craft the sql statement and commit to db.
eg:
<?php
if( isset( $_POST['content'] ) ){
$sql='insert into `<TABLE>` ( `content` ) values ( ? )';
$stmt=$db->prepare($sql);
$stmt->bind_param('s',$_POST['content']);
$stmt->execute();
$stmt->close();
exit('ok..');
}
?>
let div=document.querySelector('#content');
let bttn=document.querySelector('input[type="button"]');
bttn.addEventListener('click',e=>{
let fd=new FormData();
fd.set('content',div.innerHTML);
fetch( location.href, { method:'post', body:fd } )
.then(r=>r.text())
.then(console.log)
.catch(alert)
});
<div id="content" contenteditable="true" spellcheck="false">
hello <b>World!</b> What's occuring?
</div>
<input type='button' value='Get Contents & send to Server' />
Note: due to the sandbox restrictions here the snippet will not allow the Fetch request to localhost!