• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

133
Vistas
What is the proper way to POST data using javascript fetch?

I am trying to get away from jQuery and start using promises and arrow functions. Try as I might, I can't seem to pass data to PHP using javascript fetch.

$btnarrmem.addEventListener('click',()=>{
        let $url = "getMember.php";
        let $data = {vid: '527571'}
        $data = JSON.stringify($data);
        console.log ($data);
        fetch ($url, {
            method:'POST',
            headers :{
                'Accept': 'application/json',
                'Content-Type': 'application/json;charset=utf-8'
            },
            body:$data
        })

        .then((response)=>{
            console.log (response.text())


        })
     

The result is always

Promise {<pending>}
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: *"Notice</b>:  Undefined index: data in /mnt/development/websites/arrows/getMember.php< on line <b>7<*emphasized text**

Which means to me that PHP is not getting data.

Here is the same function written using jQuery and it works just as I want it to

let $data = {vid: '527571'}
$data = JSON.stringify($data);
console.log($data);
$('button.qrymem').click(function () {
    let $data = {vid: '527571'}
    $data = JSON.stringify($data);
    console.log ($data);
    $.post('getMember.php', {data: $data}, function ($result) {
        console.log($result);
        $divquery.text($result);
    })

})

I'd appreciate any suggestions to get me moving in the proper direction.

about 3 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

jQuery URL-encodes the data. You need to call encodeURIComponent() to do that, and then pass it as the value of the data parameter. The equivalent with fetch() is:

$btnarrmem.addEventListener('click', () => {
  let $url = "getMember.php";
  let $data = {
    vid: '527571'
  };
  $data = JSON.stringify($data);
  console.log($data);
  fetch($url, {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: `data=${encodeURIComponent($data)}`
    })

    .then((response) => {
      console.log(response.text())


    })
});

about 3 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda