------html code------
<html>
<body>
<textarea id="my-textarea"> </textarea>
<button onclick="_post_text_area_()" id="submit-btn">Submit</button>
</body>
<html>
------javascript code------
# get value of textarea
var textarea = document.getElementById("my-textarea");
function _post_text_area_() {
var data = textarea.value;
# show textarea value to console
console.log(data);
# pass data variable using fetch api POST method
fetch('_process.php', {
method: 'POST',
body: 'data=' + data
})
.then(function (response) {
return response.text();
})
.then(function (data) {
console.log(data);
});
}
--- _process.php ---
<?php
$data = $_POST['data'];
echo "Received data: " . $data;
?>
I am getting an error in _process.php file: Undefined array key 'data'. I think, i am getting this error because my javascript function is not able to create post request but I don't know the exact reason why i am getting this error.
I have tried different technique like ajax XmlHttpRequest to pass data variable to _process.php file but i got the same error.
var textarea = document.getElementById("my-textarea");
var submitBtn = document.getElementById("submit-btn");
submitBtn.addEventListener("click", function() {
var data = textarea.value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText); // Print the response from the server
}
};
xmlhttp.open("POST", "process.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("data=" + data);
});