Javascript pass more than one parameter through the fetch

Asked

Viewed 162 times

1

In the link below, I managed to send a parameter via fetch by body, but I need to send more than one, for example, values of a form.

I need an example, using POST to send through the body, for example: id: 1234, name: Test, type: payment etc, something like that.

Thanks, help.

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

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))
}


fnExibirResultado = (dados) => {
    document.querySelector('#mensagem').innerHTML = dados
}
  • Sorry I would like to add that I am trying to move to a PHP page. Getting through the data, how do I get it in PHP. Thank you.

  • edit your question and put that information there instead of adding a comment

1 answer

4

You can create an object with the values and pass in body, so for example:

var dados = {
   id: 1234, 
   nome: "Teste", 
   tipo: "pagamento"
};


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

The JSON.stringify will serialize your object with the data and pass as parameter. Note how is being passed a JSON, the header should also have this value.

  • Ricardo, as AP is using PHP, it would not be better to use the Content-Type application/x-www-form-urlencoded instead of application/json? I ask because the superglobal $_POST already supports urlencoded natively, which does not happen with the json... Continuation of this question?

  • hello Luis. Yes it would be possible, but not the way it is in the question, passing an object, would need to post the whole form, for example passing the body of fetch something like that: body: new FormData($(form)), this way would receive the form and could yes read the values using the $_POST. If you change the content by passing a json object, it must give an error of Bad Request, but would need to do a test to confirm

Browser other questions tagged

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