You would need to:
- Extract the data from the
div
usingJavaScript
- Include it in your POST request.
- Catch and handle the request in
PHP
to store it in the Database.
Example:
This is a single PHP file sample (without full page refresh), but you may need to change the part DATABASE_NAME_HERE
and also root
(which is the user-name).
<?php
if (isset($_POST['submit'])) {
// Escape possible HTML tags:
$content = htmlspecialchars($_POST['myContent'], ENT_QUOTES | ENT_SUBSTITUTE);
// Database connection.
$db = new PDO('mysql:dbname=DATABASE_NAME_HERE', 'root', '');
$db->query('CREATE TABLE IF NOT EXISTS `my_table` (id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL, text VARCHAR(1024))');
// Storing new record.
$query = $db->prepare('INSERT INTO my_table VALUES (NULL, :text)');
$query->bindValue(':text', $content);
if ($query->execute()) {
$response="Successfully stored: " . $content;
}
else {
$response="Error: " . join(' ', $query->errorInfo());
}
exit($response);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>My title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('form#my_form_id').submit(function(e) {
e.preventDefault();
const content = $('#myContent').text();
$.post('#', {submit: true, myContent: content}, function(response) {
alert(response);
});
});
});
</script>
</head>
<body>
<div id="center" style="text-align: center; margin-top: 150px;">
<div id="myContent" contenteditable="true">This is simple text</div>
<form id="my_form_id">
<input name="username">
<input type="submit" name="Send">
</form>
</div>
</body>
</html>
Note: if you want to store the entire HTML of the
div
and not just its text in above:
- Change the part
$('#myContent').text()
to$('#myContent').html()
.- Remove the
htmlspecialchars(...)
method usage (e.g.$content = $_POST['myContent'];
).
solved How to POST data to a backend server to store into database? [closed]