Read JSON from PHP with Javascript

0

I have a problem to find out how to put a Json in a cycle to read all the data of the array and generate variables with JS.

In this way I create the Json arrangement

function info(){
    global $conn;

    //Query a seleccionar en la base de datos
    $query = "SELECT permisos.idTipoMeta, tiposmetas.nombreMeta, permisos.hab FROM 'permisos' 
                INNER JOIN tiposmetas ON permisos.idTipoMeta = tiposmetas.idTipoMeta
                WHERE idUsuario = " . $_GET['idUsuario'];

    //Se ejecuta el query y si no se puede pasar a $result, hubo un problema con el query
    if(!$result = $conn->query($query)){
        die('Ha ocurrido un error ejecutando la solicitud. Error: [' . $conn->error . ']');
    }

    $output = array();

    while($tRow = $result->fetch_assoc()){
        $row = array();
        $keys = array_keys($tRow);

        for ($i = 0; $i<count($tRow); $i++){
        // if($keys[$i] != "SuspendidoProv" ){   //agregar todas las columnas excepto "SuspendidoProv" que se agregará en un input
            $row[] = $tRow[$keys[$i]];
        // }
        }

        $output['aaData'][] = $row;

    }   

    //Imprime la salida como un arreglo codificado en JSON     
    echo json_encode($output);

    $conn->close();
}

I tried to call it in the following way to put it inside a cycle for :

for (var i = 0; i < output.length; i++) {
                output[i]
            }

But it turns out that the variable is not defined. Then I checked the chrome console to know what name it is getting and it appears:

{aaData: [["1", "FACTURADO", "0"], ["2", "COBRANZA", "1"], ["3", "PROSPECTOS POTENCIALES", "1"],…]

Which means that the data is being sent, but with the name aaData but still changing by this name I can not figure out how to read this data with Javascript.

I add the code with which I link the php file with js through AJAX

$.ajax({
        dataType: "json",
        url : 'usuarios-get.php?act='+ act +'&idUsuario='+ idUsuario,
        success: function(response){

The PHP file is usuarios-get.php .

    
asked by Jose Luis Ramirez Arambul 12.12.2018 в 17:01
source

2 answers

1

If the console is literally returning

{aaData: [["1", "FACTURADO", "0"], ["2", "COBRANZA", "1"], ["3", "PROSPECTOS POTENCIALES", "1"],…]

means that you are receiving it as a string .

You should parsed the same object before traversing it.

var output = JSON.parse(output);

To make sure you only have an array test, you can also extract the data that could be wrong in the string

var output = JSON.parse(output.replace("{aaData:","").repalce("}","") );

I hope you find it useful.

    
answered by 12.12.2018 в 17:08
1

My dear, there are two circumstances to take into account:

1. jQuery and the type of response.

JQuery tells us in the documentation:

  

dataType (default: Intelligent Guess (xml, json, script, or html))

     

Type: String.

     

The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield to JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:

     

...

     

"json": Evaluates the response to JSON and returns to JavaScript object ... The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected; the server should return to a response of null or {} instead. (See json.org for more information on proper JSON formatting.)

In summary, if you specify the type of data expected as json , jQuery will return the answer already as an object of Js within the promise results ( deferred.done ), so there is no need to apply a parse .

$.ajax({
  url: 'https://mi-dominio.mx/json',
  dataType: 'json',
  success: function (object) {
    object.aaData; // se puede trabajar como objeto.
  }
});

Any other result or problem with the JSON syntax will cause an error, so even if a response has been received from the server, the success function will not be executed.

2. PHP response headers

From PHP you must indicate the response header for the type of content you return.

header('Content-Type: application/json');
echo json_encode($array);

Conclusion

In theory you should be receiving an object in the parameter of the anonymous function in success without doing anything else.

If you want to know more information about how to work with objects in Js, I recommend the following reading: Objects: the basics .

    
answered by 12.12.2018 в 17:44