0

------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);

});


  • `document.getElementById("my-textarea")` there is no element with that `id`. Did you `console.log` your `data` to see what it contains? Did you use your browser's DevTools/Network tab to see what gets sent/returned? – brombeer Feb 19 '23 at 15:51
  • “Undefined *array* 'data'” or “Undefined *array key* "data"”? – fusion3k Feb 19 '23 at 15:52
  • @brombeer this is not the problem. There was some mistake in my question. Now i have modified my question. Thanks for your comments. Now you can see understand my question properly. – user14552956 Feb 19 '23 at 16:02
  • @fusion3k i am getting this error: Undefined array key 'data' In php file. I am getting this error in $data = $_POST['data']; – user14552956 Feb 19 '23 at 16:08
  • Have you looked at [FormData](https://stackoverflow.com/a/46642899/231316) yet? – Chris Haas Feb 19 '23 at 16:09
  • @ChrisHaas Yes sir, I have tried and used FormData but still can't fix my problem. – user14552956 Feb 19 '23 at 16:12

2 Answers2

0

It is generally preferred to use FormData when creating the payload to send via fetch - the following does send the AJAX request but fails due to Sandbox limitations.

const d=document;

d.addEventListener('click',e=>{
  if( e.target instanceof HTMLButtonElement && e.target.id=='submit-btn' ){
    let fd=new FormData();
    fd.set('data', d.getElementById("my-textarea").value );

    fetch('_process.php', {method:'post',body:fd })
      .then(r=>r.text())
      .then(console.log)
      .catch(alert)
  }
});
<textarea id="my-textarea"></textarea>
<button id="submit-btn">Submit</button>
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46
0

The same code that was originally posted will only work with you set the content type appropriately. The $_POST variable was left empty for that reason.

You can change your fetch command to the following version:

fetch('_process.php', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: 'data=' + data
 })
 .then(...)
 ...

Or, you can use the application/json content type in your fetch command:

fetch('_process.php', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: 'data=' + data
 })
 .then(...)
 ...

... and in your PHP, instead of relying on the $_POST object, you do the following instead:

<?php
$postedData = json_decode(file_get_contents('php://input'), true);
$data = $postedData['data'];
echo "Received data: " . $data;
asiby
  • 3,229
  • 29
  • 32