I’m not able to send a POST to PHP by Javascript fetch

Asked

Viewed 286 times

-2

I’m trying to send a POST to PHP using fetch, the code is like this:

<button onclick="fnConsultarDadosPost()">Consultar com POST</button>
<button onclick="fnConsultarDadosGet()">Consultar com GET</button>

fnConsultarDadosPost = () => {
    const nome = document.querySelector('#nome').value

    fetch('dados.php', {
        method: 'POST',
        body: nome,
        headers: {
            'Content-Type': 'plain/text'
        }
    })
        .then(res => res.text())
        .then(res => fnExibirResultado(res))
}

fnConsultarDadosGet = () => {
    const nome = document.querySelector('#nome').value

    fetch(`dados.php?nome=${nome}`)
        .then(res => res.text())
        .then(res => fnExibirResultado(res))
}

fnExibirResultado = (dados) => {
    document.querySelector('#mensagem').innerHTML = dados
}

My backend is like this:

// Dei um var_dump do $_POST e ele retornou NULL
var_dump($_POST);

if ($_GET) {
    $nome = $_GET['nome'];

    echo "Conteúdo recebido por GET com sucesso! Seu nome é $nome";
} else if ($_POST) {
    $nome = $_POST['nome'];

    echo "Conteúdo recebido por POST com sucesso! Seu nome é $nome";
}

Completion:

When I use the GET, He returns me right, but when I use the POST it doesn’t even get into PHP. I’m forgetting something in the syntax of POST?

1 answer

4


The $_POST of PHP presupposes chave=valor in the body, or a Multipart request. In the first case you need to use the type application/x-www-form-urlencoded, in the second multipart/form-data.

You are only sending the value on the body. Either hit the POST or recover with the php://input.

See the difference with these lines:

'Content-Type': 'application/x-www-form-urlencoded'

and

const nome = 'nome=' + document.querySelector('#nome').value
//           ^^^^^^^^^^

Click on Run:

fnConsultarDadosPost = () => {
    const nome = 'nome=' + document.querySelector('#nome').value

    fetch('https://httpbin.org/post', {
        method: 'POST',
        body: nome,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    })
        .then(res => res.text())
        .then(res => fnExibirResultado(res))
}

fnConsultarDadosGet = () => {
    const nome = document.querySelector('#nome').value

    fetch(`https://httpbin.org/get?nome=${nome}`)
        .then(res => res.text())
        .then(res => fnExibirResultado(res))
}

fnExibirResultado = (dados) => {
    document.querySelector('#mensagem').innerHTML = dados
}
<input id="nome" value="biriba">
<button onclick="fnConsultarDadosPost()">Consultar com POST</button>
<button onclick="fnConsultarDadosGet()">Consultar com GET</button>

<pre id="mensagem"></pre>

Or, on the PHP side you will have to do something like this:

$hndl = fopen("php://input", "r");
$data = fread($hndl, 1024); // Talvez um loop se a informação for longa
  • Very interesting! You helped many people today my friend, thank you for sharing this knowledge. What is the most indicated in these cases? Use this concatenation right there in javascript or recover in PHP as you explained?

  • In principle the two work, and not much changes in the sending mechanism. There’s no "better," you have to see which one looks best in the context you’re going to use.

Browser other questions tagged

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