JSON sent from PHP and read it in JAVASCRIPT

1

I have implemented a function in javaScript that takes the indicated value and then queries it with php in the database but when I came back with a php JSON and read it in javaScript I can not get the data

JavaScript Code:

function capturar(){
    var celular = document.getElementById("celular").value;
    $.post("php/listarInformes.php", { celular: celular}, function(data){
        var datos = data;
        alert(datos.nombres);
    });
}

PHP Code:

<?php

session_start();

include "conexion.php";
include "funciones.php";


if(isset($_POST["documento"]) || isset($_POST['celular'])){

    $datos='';



    if(!empty($_POST['celular'])){

        //INFORMES
        $sql = "SELECT * FROM informes WHERE celular='".$_POST['celular']."';";
        $resultado = mysqli_query($conexion,$sql);
        $fila = mysqli_fetch_array($resultado,MYSQLI_ASSOC);

        if(empty($fila['codigo'])){

            //CLIENTE
            $sql = "SELECT * FROM cliente WHERE celular='".$_POST['celular']."';";
            $resultado = mysqli_query($conexion,$sql);
            $fila = mysqli_fetch_array($resultado,MYSQLI_ASSOC);

            if(empty($fila['codigo'])){



            }else{

                //CLIENTE
                $datos=array(
                    "documento"=>"".$fila['dni']."",
                    "nombres"=>"".$fila['nombres']."",
                    "apellidos"=>"".$fila['apellidos']."",
                    "fecha de nacimiento"=>"".$fila['fechaNacimiento'].""
                );




            }
        }else{

            //INFORMES
            $datos=array(
                "documento"=>"".$fila['dni']."",
                "nombres"=>"".$fila['nombres']."",
                "apellidos"=>"".$fila['apellidos']."",
                "fecha de nacimiento"=>"".$fila['fechaNacimiento'].""
            );

        }

    }



    echo json_encode($datos, JSON_PRETTY_PRINT);

}




?>
    
asked by Eduardo Castro 06.10.2018 в 14:47
source

3 answers

1

I think the error occurs because you are not indicating to PHP the type of data that should return. I would try the following:

<?PHP

$json['dato1']=$dato1;
$json['dato2']=$dato2;


// Aquí se define en la cabecera de la respuesta el tipo de dato a retornar.
header('Content-Type: application/json');
echo json_encode($json);
    
answered by 06.10.2018 в 17:28
0

Assuming that the PHP output is correct, what you need is for JS to "digest" that JSON to Object Literal :

function capturar(){
    let celular = document.getElementById("celular").value,
        json;
    $.post("php/listarInformes.php", { celular: celular}, function(data){
        //var datos = data; ¡no es necesario crear una variable que está creada ya!
        console.log(data); //esto muestra la respuesta de PHP en crudo, directo en la consola
        json = JSON.parse(data);
        console.log(json);
        console.log(json.personas);
    });
}

Press F12 if you use Chrome to open the console, there you can see the result. If the problem is in PHP please share a little more of the output generated by your script.

    
answered by 07.10.2018 в 02:57
0

When the server sends the JSON the browser receives it as a string, so its properties can not be read, but we can use JSON.parse to evaluate the string and return the corresponding object to the JSON received.

Try it replacing the line that says

var datos = data;

for this:

var datos = JSON.parse(data);

Good luck!

    
answered by 06.10.2018 в 22:09