-2

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

Alejandro
  • 3
  • 3

3 Answers3

0

I have made some proper way for this method to get working. You need to make an object first, then pass it in 'for loop'. It will generate string like this for example (test=123&test_two=444)

async function catch_something(url, bodyContent = {test: 123, test_two: 444}){
let bodyContent_string = '';
if(bodyContent instanceof Object){
    for(const form_key of Object.keys(bodyContent)){
        if(form_key != Object.keys(bodyContent)[Object.keys(bodyContent).length - 1]){
            bodyContent_string += `${form_key}=${bodyContent[form_key]}&`;
        }else{
            bodyContent_string += `${form_key}=${bodyContent[form_key]}`;
        }
    }
}
const response = await fetch(url, {
    method: 'POST',
    mode: 'cors',
    cache: 'no-cache',
    headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: bodyContent_string
}).catch((error) => {
    console.error('Error:', error);
});
if(!response.ok){
    throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
}
-1

You've passed a plain object to the body parameter, but fetch doesn't know what to do with that data type (so it converts it to the useless string "[object Object]").

You should pass something that fetch knows how to convert into something supported by PHP instead.

e.g. a FormData object.

DatosPaciente = new FormData(document.getElementById("form_containing_your_inputs"));
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • throws me the following: Uncaught TypeError: Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'. – Alejandro Sep 03 '20 at 23:05
  • @Alejandro — Then the element with the ID “form_containing_your_inputs” isn’t a form that contains your inputs! Make sure it is one! – Quentin Sep 03 '20 at 23:17
  • Sorry I'm relatively new to developing with javascript, I don't know how to do that, where can I find that information? – Alejandro Sep 03 '20 at 23:21
-1

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);
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • throws me the following: Uncaught ReferenceError: getElementById is not defined – Alejandro Sep 03 '20 at 23:23
  • Sorry, that was a copying error. Of course it's supposed to be `document.getElementById` – Barmar Sep 03 '20 at 23:25
  • that solved the error and now DatosPaciente: console.log(Datos);=id=8&fecha=2020%2F09%2F04, but apparently the information still does not get to the PHP file, because it returns the following: **SELECT * FROM vhsagenda WHERE PACIENTE='' AND FECHA=''** – Alejandro Sep 03 '20 at 23:36
  • Try sending the header `Content-Type: application/x-www-form-urlencoded` – Barmar Sep 03 '20 at 23:38
  • excuse my ignorance, where? – Alejandro Sep 03 '20 at 23:52
  • In the `headers:` option to `fetch()`. https://stackoverflow.com/questions/38156239/how-to-set-the-content-type-of-request-header-when-using-fetch-api – Barmar Sep 03 '20 at 23:52
  • Finally it works **"SELECT * FROM vhsagenda WHERE PACIENTE='8' AND FECHA='2020/09/04'** Thank you – Alejandro Sep 04 '20 at 00:04
  • 1
    Now you need to learn to use prepared statements in PHP. – Barmar Sep 04 '20 at 00:07