
ayuda con envio de variable con fetch API
Publicado por Marcelino (2 intervenciones) el 14/09/2024 19:58:25
tengo estos codigos para solucionar un problema de envio de variable via post al formulario consulta.php
y este es el codigo del formulario consulta.php:
El asunto es que no esta trayendo este ultimo formulario consulta.php podrian ayudarme con este caso porque estoy iniciandome con esto del FETCH API.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap demo</title>
</head>
<body>
<form name="form1" action="" method="post" accept-charset="utf-8">
<table width="200" align="center" class="bordetbl1">
<tr>
<td class="tit1">Nro Historia:</td>
<td><input type="text" name="nrohistoria" id="nrohistoria" size="8"></td>
<td><button type="button" id="buscar">Buscar</button></td>
<td><button type="button" onclick="window.location.href='menu1.php'">Salir</button></td>
</tr>
</table>
</form>
<div id="response-container"></div>
<script>
// ... your JavaScript code ...
let nroHistoria = document.getElementById("nrohistoria").value;
let responseContainer = document.getElementById("response-container");
fetch("consulta.php", {
method: "POST",
body: `nrohistoria=${encodeURIComponent(nroHistoria)}`,
headers: { "Content-Type": "application/x-www-form-urlencoded" }
})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.text(); // Obtener la respuesta como texto plano
})
.then(data => {
try {
const jsonData = JSON.parse(data);
console.log(jsonData);
responseContainer.textContent = jsonData.message;
} catch (error) {
console.error("Error al parsear el JSON:", error);
responseContainer.textContent = "La respuesta del servidor no es un JSON válido.";
}
})
</script>
</body>
</html>
y este es el codigo del formulario consulta.php:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?php
$connect = pg_connect("host=localhost port=5432 dbname=pediatria user=postgres password=****");
// Preparar la consulta SQL de forma segura (usando parámetros)
$query = "SELECT * FROM pacientes WHERE nrohistoria = $1";
$result = pg_prepare($connect,$query);
$result = pg_execute($connect, array($nroHistoria));
// Obtener los datos del paciente
$row = pg_fetch_assoc($result);
// Validar si se encontró un resultado
if ($row) {
// Crear un JSON con la información relevante
$data = [
'nroHistoria' => $row['nroHistoria'],
// Agrega más campos según sea necesario
];
// Enviar el JSON como respuesta
header('Content-Type: application/json');
echo json_encode($data);
} else {
// Si no se encontró el paciente, enviar un mensaje de error
http_response_code(404);
echo json_encode(['error' => 'Paciente no encontrado']);
}
?>
<TABLE align="center" class="bordetbl1">
<TR bgcolor="#99CCCC">
<TD align="left" class="tit1">Nro Historia:</TD>
<TD class="tit1">
<input type='text' name='nrohistoria' readonly=".f." size="10" maxlength="10" value="<?php echo $historia ; ?>"/>
<!-- <input type="submit" name="buscar" value="Buscar">
--> <?php echo "<a href='pacientes.php' class='tit1'>Volver al modulo de Inclusion del Nro Historia</a>"?>
</TD>
</TR>
</TABLE>
Valora esta pregunta


0