How To Post Data To A Backend Server To Store Into Database?
Solution 1:
You can use XMLHttpRequest to communicate with servers.
Use XMLHttpRequest (XHR) objects to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing. XMLHttpRequest is used heavily in AJAX programming.
Here is an example
// Read your data inside the HTML DIV using the IDvar content = document.getElementById('myContent').innerHTML;
// Add the contents to the object which you want to send to the backendvar data = { "myContent": content };
var xmlhttp = newXMLHttpRequest(); // new HttpRequest instance var theUrl = "/json-handler"; // The backend URL which expects your data
xmlhttp.open("POST", theUrl);
// Set the request format
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
// JSON encode the data by stringifying it before sending to the server
xmlhttp.send(JSON.stringify(data));
Solution 2:
let myData=$('#myContent').html();
$.ajax({
method:'POST',
url : 'put your file path where do want to handle data',
data:{
'data':myData
},
success:function(returnMsg){
console.log("Success Msg",returnMsg)
}
})
Solution 3:
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).
<?phpif (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'];
).
Solution 4:
You need use AJAX send your data (if you need more info, see it: Introduction to Ajax - IBM)
so:
- Get your DOM data -- use javascript code;
- Send your data to server API;
- Server save the data.
xmlHttp / jQuery AJAX / Axios / etc. you can choice anyone AJAX tool.
Solution 5:
HTML
<div id="myContent" contenteditable="true">This is a simple text</div>
Jquery :
var data = $("#myContent").html();
var url = "--your url here--";
$.post(url,
{
html: data
},
function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
PHP
$db = mysqli_connect("localhost", "dbusername", "dbpass", "dbname");
$html_data = mysqli_real_escape_string($db, $_POST["html"]);
mysqli_query($db, "INESRT INTO MYTABLE(html_data) VALUES('$html_data')");
Post a Comment for "How To Post Data To A Backend Server To Store Into Database?"