A
A
Anonymous Penguin2022-04-17 19:58:11
PHP
Anonymous Penguin, 2022-04-17 19:58:11

Why are POST parameters not being passed?

I pass POST parameters, but PHP does not see them, it displays only a test string. Tried with GET, everything worked as it should.
JS

fetch('test.php', {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({ code }) // { code:string }
})

PHP
<?
echo 'Test'; // Тестовая строка, выводится
echo $_POST['code']; // Не выводится


Here with GET:
JS
fetch( 'test.php?' + new URLSearchParams({ code }) );

PHP
<?
echo $_GET['code']; // Работает

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
TheAndrey7, 2022-04-17
@Anopeng

Because the variable $_POSTcan only work with application/www-x-form-urlencoded and multipart/form-data . The custom type Body as JSON already needs to be obtained and parsed by handles.

<?php
$json = json_decode(file_get_contents('php://input'), true);
var_dump($json);

If you still want through $_POST, you need to pass the request body through FormData , instead of JSON.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question