I am passing javascript variable to php using fetch api method post but in php file i am getting error: undefined array key 'data'. How to fix it?

huangapple go评论56阅读模式
英文:

I am passing javascript variable to php using fetch api method post but in php file i am getting error: undefined array key 'data'. How to fix it?

问题

<html>
<body>
 <textarea id="my-textarea"> </textarea>
 <button onclick="_post_text_area_()" id="submit-btn">提交</button>
</body>
<html>
# 获取文本框的值
var textarea = document.getElementById("my-textarea");

function _post_text_area_() {       
    var data = textarea.value;
    # 在控制台显示文本框的值
    console.log(data);

    # 使用 fetch API  POST 方法传递 data 变量
    fetch('_process.php', {
             method: 'POST',
             body: 'data=' + data
       })
       .then(function (response) {
          return response.text();
       })
       .then(function (data) {
           console.log(data);
           });
}
<?php
$data = $_POST['data'];
echo "接收到的数据: " . $data;
?>

在 _process.php 文件中出现了错误:未定义数组键 'data'。我认为,我之所以出现这个错误,是因为我的 JavaScript 函数无法创建 POST 请求,但我不知道为什么会出现这个错误。

我尝试过不同的技巧,比如使用 Ajax XmlHttpRequest 来将 data 变量传递给 _process.php 文件,但我仍然得到了相同的错误。


<details>
<summary>英文:</summary>

**------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(&#39;_process.php&#39;, {
         method: &#39;POST&#39;,
         body: &#39;data=&#39; + 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 &#39;data&#39;. I think, i am getting this error because my javascript function is not able to create post request but I don&#39;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 &amp;&amp; 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);

});


</details>


# 答案1
**得分**: 0

以下是翻译好的部分:

```javascript
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>
英文:

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.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const d=document;

d.addEventListener(&#39;click&#39;,e=&gt;{
  if( e.target instanceof HTMLButtonElement &amp;&amp; e.target.id==&#39;submit-btn&#39; ){
    let fd=new FormData();
    fd.set(&#39;data&#39;, d.getElementById(&quot;my-textarea&quot;).value );

    fetch(&#39;_process.php&#39;, {method:&#39;post&#39;,body:fd })
      .then(r=&gt;r.text())
      .then(console.log)
      .catch(alert)
  }
});

<!-- language: lang-html -->

&lt;textarea id=&quot;my-textarea&quot;&gt;&lt;/textarea&gt;
&lt;button id=&quot;submit-btn&quot;&gt;Submit&lt;/button&gt;

<!-- end snippet -->

答案2

得分: 0

原先发布的代码只有在适当设置内容类型时才能正常工作。$_POST 变量之所以为空是因为这个原因。

您可以将您的 fetch 命令更改为以下版本:

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

或者,您可以在 fetch 命令中使用 application/json 内容类型:

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

... 并且在您的 PHP 代码中,不再依赖于 $_POST 对象,而改为执行以下操作:

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

只提供代码部分的翻译。

英文:

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(&#39;_process.php&#39;, {
    method: &#39;POST&#39;,
    headers: {
        &#39;Content-Type&#39;: &#39;application/x-www-form-urlencoded&#39;
    },
    body: &#39;data=&#39; + data
 })
 .then(...)
 ...

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

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

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

&lt;?php
$postedData = json_decode(file_get_contents(&#39;php://input&#39;), true);
$data = $postedData[&#39;data&#39;];
echo &quot;Received data: &quot; . $data;

huangapple
  • 本文由 发表于 2023年2月19日 23:44:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/75501317.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定