I am trying to just sent some POST data via fetch to a PHP endpoint and want PHP to just output the _POST details.
e.preventDefault();
(async () =>
{
const response = await fetch('form-api.php',
{
method: 'POST',
body: JSON.stringify({a: 1, b: 'Textual content'})
});
const content = await response.json();
console.log(content);
})();
form-api.php : <?php echo json_encode($_POST) ?>
But content is always []
I understand I can get it via :
$json_str = file_get_contents('php://input');
$json_obj = json_decode($json_str);
But I want to know why $_POST is empty. It isn't when I use jQuery's AJAX like this.
$.ajax(
{
url : "<?php echo CB_ABS_URI ?>ajax/change-bp-name.php",
type: "POST",
dataType: "json",
data: { BPID: "<?php echo $BPID ?>", Name: $('#txt-bp-name').val() },
success : function(data, textStatus, jqXHR)
{
if (data['Status'] == 'Error')
{
alert(data['Message']);
}
else
{
// alert(data['Message']);
}
}
});
My Answer:
> In JavaScript, when using the `fetch` API to send POST data to a PHP endpoint, the data is sent in the request body, not as form data like in a traditional form submission. This means that the data will not be available in the `$_POST` superglobal array in PHP.
To access the POST data sent via fetch in PHP, you need to read the raw input stream. Here's an example of how you can do this:
javascript
e.preventDefault();
(async () => {
const formData = new FormData();
formData.append('key1', 'value1');
formData.append('key2', 'value2');
const response = await fetch('your_php_endpoint.php', {
method: 'POST',
body: formData
});
const data = await response.text();
console.log(data);
})();
In your PHP endpoint, you can access the POST data like this:
php
$input = file_get_contents('php://input');
$postData = json_decode($input, true);
print_r($postData);
By reading the raw input stream and decoding it as JSON, you can access the POST data sent via fetch in PHP.
Rate this post
4 of 5 based on 3231 votesComments