Search code examples
phpfetch

The variables never reach PHP from the FETCH API


I have 3 files (HTML,JS and PHP) in the HTML save de info in variable called DatosPaciente in JavaScript

function Tomar_DATOS(){            
  DatosPaciente={
    id:document.getElementById("paciente_id").value,
    fecha:document.getElementById("fecha").value
};}

Then i use a function called Tiene_Cita_Hoy inside of a JS file

Tiene_Cita_Hoy(DatosPaciente)

in the JS file i try to use the Fetch API to send info to the PHP file

function Tiene_Cita_Hoy(Datos){
console.log(Datos);//"{id: "8", fecha: "2020/09/03"}" here everything is fine
    fetch('tiene_cita.php',{
        method: 'POST',
        body: Datos
    })                           
        .then(res => res.json()) 
        .then(data => {                     
            console.log(data); //to see the result
        })
 }        

then in a PHP file, then tried to receive the information via POST

  $VALOR_id_paciente=$_POST['id']; 
  $VALOR_fecha=$_POST['fecha'];

and then I assign those values ​​to a query

$SQL="SELECT * FROM vhsagenda WHERE PACIENTE='".$VALOR_id_paciente."' AND FECHA='".$VALOR_fecha."'";
echo json_encode($SQL);//just to see what information have

but the result is always: SELECT * FROM vhsagenda WHERE PACIENTE='' AND FECHA=''

apparently the information never reaches the PHP file


Solution

  • You should send the parameters as a URL-encoded string.

    function Tomar_DATOS(){            
      DatosPaciente = 'id=' + encodeURIComponent(document.getElementById("paciente_id").value) + '&fecha=' + encodeURIComponent(document.getElementById("fecha").value);
    }