How to receive with $_POST in PHP a value that was sent via Urlsearchparams (urlencoded) with Javascript Vanilla fetch?

Asked

Viewed 57 times

-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 defined application/x-www-form-urlencoded by the use of URLSearchParams (just like you did) and I received correctly, by PHP, the parameter id_plano.

  • Managed to receive $_POST ?

  • As I said above, yes. Here’s what I did.

  • Poxa, exactly the same. I don’t know why in my example it doesn’t work.

  • @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 the fetch 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, 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.

  • Have you checked the request headers to see how and what data is coming?

  • @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.

  • @Gatodeschrödinger, but it already escapes the question, doesn’t it? After all, the data are, in fact, being received by PHP! :-)

  • @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.

  • ... After I entered the then(), the data started to arrive in the PHP file.

Show 6 more comments

2 answers

-1


The problem was that I was not using "then()". For being a Promisse, fetch() requires the use of "then()" to return your resolves(), or "catch()", so that your Reject().

Follows below the two forms I managed to do, both with the Urlsearchparams so much with the formData:

FormData

let optionSelected = selectPlanoDecontas.options[e.target.options.selectedIndex].value

let form = new FormData()

form.append('id_plano', optionSelected)

fetch('../php/listar-classificacoes-por-plano.php', {
  method: 'POST',
  body: dataForm
})
.then(response => {

}) 
.catch(error => {

})

With Urlsearchparams

let optionSelected = selectPlanoDecontas.options[e.target.options.selectedIndex].value

fetch('../php/listar-classificacoes-por-plano.php', {
    method: 'POST',
  body: new URLSearchParams({
    id_plano: optionSelected
  })
})
.then(response => {
  
})
.catch(error => {

})

These are the two ways I’ve found to do (there are others). With both formData and Urlsearchparams.

-1

O . then and . catch treat the backend response

Data is not coming when I try to pick up $_POST.

I reproduced something similar to what you probably use in your Vanilla JS

<?php
// test.php

$idPlano = filter_input(INPUT_POST, 'id_plano', FILTER_SANITIZE_STRING);

echo '<pre>';
echo 'var_dump(idPlano): ';
echo PHP_EOL;
var_dump($idPlano);

echo PHP_EOL;
echo 'var_dump($_POST): ' ;
echo PHP_EOL;
var_dump($_POST);

File . html

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <select id="select-teste">
        <option value="valor_1">Valor 1</option>
        <option value="valor_2">Valor 2</option>
    </select>
</body>
<script type="text/javascript">

    var selected = document.getElementById('select-teste');
    selected.onchange = function(selected) { 
        let optionSelected = this.options[selected.target.options.selectedIndex].value;
        
        fetch('test.php', {
            method: 'POST',
            body: new URLSearchParams({
                id_plano: optionSelected
            })
        });

    }
    
</script>
</html>

See the var_dump output

var_dump

That is, the data arrives in the back-end. That done yes you process your logic and returns the answer to that with . then and . catch you treat in front-end

Browser other questions tagged

You are not signed in. Login or sign up in order to post.