-2
I would like to know how to receive the data in php with $_POST, and the data comes from a request that is sent via JS Fetch. With Formdata (Multipart/form-data) I get good.
The problem is that in my case the value comes from a variable. I think it would not be feasible to use formData for this. So I opted for Urlsearchparams (urlencoded), but I do not succeed. The data is not coming when I try to get $_POST.
JS Code:
let optionSelected = selectPlanoDecontas.options[e.target.options.selectedIndex].value
fetch('../php/listar-classificacoes-por-plano.php', {
method: 'POST',
body: new URLSearchParams({
id_plano: optionSelected
})
})
PHP code
$idPlano = filter_input(INPUT_POST, 'id_plano', FILTER_SANITIZE_STRING);
print_r($idPlano);
That way below also doesn’t work:
$idPlano = $_POST['id_plano'];
print_r($idPlano);
From now on, thank you.
I could not reproduce this problem. I sent the same request (using
fetch
with Content-Type definedapplication/x-www-form-urlencoded
by the use ofURLSearchParams
(just like you did) and I received correctly, by PHP, the parameterid_plano
.– Luiz Felipe
Managed to receive $_POST ?
– Gato de Schrödinger
As I said above, yes. Here’s what I did.
– Luiz Felipe
Poxa, exactly the same. I don’t know why in my example it doesn’t work.
– Gato de Schrödinger
@Gatodeschrödinger How are you doing to know that
print_r($idPlano);
not working? directly access the url../listar-classificacoes-por-plano.php
will not work because thefetch
does not reload the page when executing. One option would be to use your browser’s developer tools to know what the server is responding to.– Juven_v
@Juven_v, I do it directly in the file. Although I don’t reload the page, fetch does the request to the file, right? So, accessing the php file, I believe you can see this print_r output in "Network", which is what I’m doing.
– Gato de Schrödinger
Have you checked the request headers to see how and what data is coming?
– Augusto Vasques
@Augustovasques, had checked yes. It was all right. Status, etc ... The problem was that I was not using the then. I will elaborate an answer.
– Gato de Schrödinger
@Gatodeschrödinger, but it already escapes the question, doesn’t it? After all, the data are, in fact, being received by PHP! :-)
– Luiz Felipe
@Luizfelipe, no, they were not. It was only received after we used then() no fetch(). For an inexplicable reason (or understandable by the promisse issue), fetch only completes the request, and sends the data to the backend when it has a then() to ensure the return of its promisse. Or another then(), who receives your return and treats you.
– Gato de Schrödinger
... After I entered the then(), the data started to arrive in the PHP file.
– Gato de Schrödinger