Uncaught SyntaxError: Unexpected token a in JSON at position 0 at JSON.parse (<anonymous>) a
Publicado por Angel (9 intervenciones) el 17/09/2020 20:17:43
Estoy realizando un proyecto con php, js, ajax y mysql. Al realizar la peticion ajax desde js recivo este error.
Uncaught SyntaxError: Unexpected token a in JSON at position 0
at JSON.parse (<anonymous>)
at XMLHttpRequest.xhr.onreadystatechange (validarformulario.js:34)
JS
PHP
Uncaught SyntaxError: Unexpected token a in JSON at position 0
at JSON.parse (<anonymous>)
at XMLHttpRequest.xhr.onreadystatechange (validarformulario.js:34)
JS
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
const form = document.getElementById('añadircontactos').addEventListener("submit", leerformulario);
function leerformulario(evt) {
const nombre = document.getElementById('nombre').value;
const empresa = document.getElementById('empresa').value;
const telefono = document.getElementById('telefono').value;
var infocontacto = new FormData();
infocontacto.append('nombre', nombre);
infocontacto.append('empresa', empresa);
infocontacto.append('telefono', telefono);
if (nombre == "" || empresa == "" || telefono == "") {
console.log('Todos los campos son obligatorios')
} else {
insertardb(infocontacto);
}
evt.preventDefault();
}
function insertardb(datos) {
let xhr = new XMLHttpRequest();
xhr.open("POST", "modelo-contactos.php", true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var respuesta = JSON.parse(xhr.responseText);
console.log(respuesta);
var añadirtareas = document.getElementById('añadirtareas');
añadirtareas.innerHTML=`
<td class="tabla">${respuesta.datos.nombre}</td>
<td class="tabla">${respuesta.datos.empresa}</td>
<td class="tabla">${respuesta.datos.telefono}</td>`
;
}
}
xhr.send(datos);
}
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
<?php
require_once("conexionbd.php");
$nombre = filter_var($_POST['nombre'], FILTER_SANITIZE_STRING);
$empresa = filter_var($_POST['empresa'], FILTER_SANITIZE_STRING);
$telefono = filter_var($_POST['telefono'], FILTER_SANITIZE_STRING);
echo("$nombre $empresa $telefono");
try {
$statement = $conexion->prepare("INSERT INTO contactos(usuario, empresa, telefono) VALUES (?, ?, ?)");
$statement -> bind_param("sss", $nombre, $empresa, $telefono);
$statement -> execute();
$respuesta = array(
'respuesta' => 'correcto',
'datos' => array(
'nombre' => $nombre,
'empresa' => $empresa,
'telefono' => $telefono
)
);
$statement->close();
$conexion->close();
} catch (Exception $e) {
$respuesta = "Operacion fallida" + $e->getMessage();
}
echo json_encode($respuesta);
Valora esta pregunta


0