Hi I am creating my own CRUD, using fetch requests, when I am returning the data I am painting them by console but I get the following error
SyntaxError: "undefined" is not valid JSON at JSON.parse () at envio_datos_registro_usuarios.js:19:33
. I tried with ajax and everything works fine, but I want to learn how to handle fetch. Thank you very much for reading and helping me!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" >
<link rel="stylesheet" href="css/estilos.css">
<title>Creacion de Usuario</title>
</head>
<body>
<header class="header">
<img src="" alt="banner">
</header>
<main>
<div class="contenedor">
<h1>Creación de Usuario</h1>
<div class="contenedor-login-nuevo-usuario">
<!-- <div class="imagen-login">
<img src="img/usuarios.png" alt="imagene-sesion">
</div> -->
<form id="formulario-nuevo-usuario">
<div class="campos">
<label for="nombre">Nombre:</label>
<input type="text" name="nombre" title="Solo se aceptan letras" pattern="^[A-Za-zÑñÁÉÍÓÚáéíúóÜ\s]+$" required>
</div>
<div class="campos">
<label for="apellido">Apellido:</label>
<input type="text" name="apellido" title="Solo se aceptan letras" pattern="^[A-Za-zÑñÁÉÍÓÚáéíúóÜ\s]+$" required>
</div>
<div class="campos">
<label for="email">Correo:</label>
<input type="email" name="email" pattern="^[a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,15})$" title="Email incorrecto" required>
</div>
<div class="campos">
<label for="user">Usuario:</label>
<input type="text" name="user" title="El usuario es requerido" required>
</div>
<div class="campos">
<label for="password">Contraseña:</label>
<input type="password" name="password" required>
<span id="requisitos-password" class="contact-form-error none">
<h4>La contraseña debe cumplir con los siguientes requisitos:</h4>
<ul>
<li id="mayuscula" class="invalido">Al menos una letra mayúscula</li>
<li id="number" class="invalido">Al menos un número</li>
<li id="blank" class="invalido">Sin espacios en blanco</li>
<li id="length" class="invalido">Tener 6 caracteres</li>
</ul>
</span>
</div>
<div class="campos">
<label for="password">Confirmar Contraseña:</label>
<input type="password" name="password2" required>
</div>
<div class="contenedor-btn">
<button type="submit" id="boton-registrar" name="boton-registrar" value="Registrar">Crear</button>
</div>
</form>
</div>
</div>
</main>
</body>
<script src="js/sweetalert2.all.min.js"></script>
<script src="./js/envio_datos_registro_usuarios.js" ></script>
</html>
Mi JS
const d=document;
d.addEventListener('DOMContentLoaded', e=>{
sendDatosForm();
})
function sendDatosForm () {
let $btnRegistro=d.getElementById('boton-registrar');
$btnRegistro.addEventListener('click', e=>{
e.preventDefault();
const datos=new FormData(d.getElementById('formulario-nuevo-usuario'));
fetch('./modelo/registrar_usuarios.php', {
method: 'POST',
body: datos,
headers:{
'Content-Type': 'application/json'
}
})
.then(res=>{return res.ok ?(res.json(), console.log(res)) :Promise.reject(res);})
.then(data=>{console.log(JSON.parse(data))})
.catch(err=>{
console.log(err);
})
.finally(()=>{
console.log('Esto se ejecutará independientemente del resultado de la Promesa Fetch')
})
})
} PHP
<?php
$respuesta= array('respuesta' =>'Hello there' , );
echo json_encode($respuesta);
?>