0

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);
?>
  • `(res.json(), console.log(res))` is an expression that results in `undefined`. You want `(console.log(res), res.json())` if anything. See [What does the comma operator do in JavaScript?](/q/3561043/4642212). Also, read the [documentation](//developer.mozilla.org/en/docs/Web/API/Response/json). Your additional [`JSON.parse`](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) call is incorrect. – Sebastian Simon Nov 22 '22 at 23:57
  • The error is not in the comma, since the browser tells me that in line 19 where is the return of the data, which gives me the undefined regardless of removing the JSON.parse. I use the comma to separate two statements in the ternary operator. Besides, if it were the comma, the error would not appear in the consolé.log(res), that is to say, this console would not be fired ? – Kenlymar Paredes Nov 23 '22 at 00:26
  • 1
    @KenlymarParedes `(1,2)` evaluates to `2` in javascript. – Evert Nov 23 '22 at 00:29
  • @Evert sorry but I don't follow you – Kenlymar Paredes Nov 23 '22 at 00:33
  • 1
    @KenlymarParedes `console.log('..')` returns `undefined` so `(res.json(), console.log(res))` returns `undefined` – Evert Nov 23 '22 at 00:36
  • 1
    In other words, the comma operator only returns the _last_ item in the list. (1,2,3) returns 3. – Evert Nov 23 '22 at 00:39

0 Answers0